Booleans
Understanding truthy and falsy values in JavaScript is essential because JavaScript uses implicit type coercion when evaluating expressions in a boolean context. Here’s a deeper dive with examples.
Falsy values are values that evaluate to false
in a boolean context. There are only a few of these in JavaScript, and they are:
false
– The booleanfalse
.if (false) console.log("This will not run");
0
– The number zero (also-0
).if (0) console.log("This will not run");
""
– An empty string (''
or""
or even a template literal ``````).if ("") console.log("This will not run");
null
– Represents the intentional absence of any object value.if (null) console.log("This will not run");
undefined
– Indicates a variable that has been declared but not assigned a value.if (undefined) console.log("This will not run");
NaN
– Not-a-Number, often the result of invalid math operations.if (NaN) console.log("This will not run");
Here’s a simple example of falsy values in action:
let values = [false, 0, "", null, undefined, NaN];
values.forEach(value => {
if (!value) {
console.log(`${value} is falsy`);
}
});
Any value that is not falsy is considered truthy. This includes all non-zero numbers, non-empty strings, objects, arrays, and even the true
boolean value.
Some common truthy values:
Non-zero numbers (both positive and negative):
if (1) console.log("This will run"); if (-1) console.log("This will also run");
Non-empty strings:
if ("Hello") console.log("This will run"); if ("false") console.log("Even this string will run");
Objects (including arrays, functions, and other objects):
if ({}) console.log("This will run"); if ([]) console.log("This will also run");
true
– The booleantrue
.if (true) console.log("This will run");
Here’s a simple example of truthy values in action:
let values = [1, -1, "Hello", {}, [], true];
values.forEach(value => {
if (value) {
console.log(`${value} is truthy`);
}
});
JavaScript allows us to use these implicit truthy/falsy values in conditions, which is handy for quickly checking if a variable is set or has content.
let name = "Alice";
if (name) {
console.log("Name is set"); // This will run because "Alice" is truthy.
}
let emptyName = "";
if (!emptyName) {
console.log("Name is empty"); // This will run because "" is falsy.
}
Understanding truthy and falsy values helps write concise and readable code, particularly when performing conditional checks without explicit == true
or == false
. However, be cautious with implicit conversions, as they can sometimes lead to unexpected results if not properly understood.