Truthy and Falsy
In JavaScript, you do not need to explicitly convert a value to a boolean before using it in a conditional statement like an if block. JavaScript automatically evaluates values as either “truthy” or “falsy”.
Truthy Values
A truthy value is one that evaluates to true when encountered in a boolean context.
if ("hello") {
console.log("hello is truthy");
}
if (42) {
console.log("42 is truthy");
}
Common truthy values include:
true42(Any number that is not0)"hello"(Any non-empty string)[](An empty array){}(An empty object)function() {}(An empty function)
Falsy Values
A falsy value evaluates to false. If you place a falsy value inside an if statement, the block will not execute.
if (0) {
// This will never execute
console.log("0 is falsy");
}
There are exactly 6 common falsy values in JavaScript. It is highly recommended to memorize this list:
false0(The number zero)""(An empty string)nullundefinedNaN(Not a Number)
Practical Example
Because numbers other than 0 are truthy, you can use numeric variables directly in if statements to check if a user has sufficient quantity of an item. However, you must be careful with negative numbers, as they are also truthy!
// A bug: -2 is truthy, so the condition evaluates to true!
const userCredits = -2;
// To fix this, you should explicitly check > 0 rather than relying on truthiness alone
if (userCredits > 0) {
console.log("Processing action...");
} else {
console.log("Not enough credits.");
}