Falsy Values in JavaScript
Published: Monday, May 16, 2022
Greetings, friends! When working with Boolean contexts such as in if statements and for loops, you'll need to know what values make the condition fail due to a falsy value. The most common falsy values you'll encounter when coding in JavaScript are the following:
- The
falseboolean value - The number
0 - An empty string using double quotes
"", single quotes'', or a template literal - The
nullvalue - The
undefinedvalue NaN(not a number)
All of these values will cause a boolean condition to fail:
javascript
if (false) {
console.log('1. You will see me if the condition is truthy.');
} else {
console.log('1. You will see me if the condition is falsy.');
}
if (0) {
console.log('2. You will see me if the condition is truthy.');
} else {
console.log('2. You will see me if the condition is falsy.');
}
if ("") {
console.log('3. You will see me if the condition is truthy.');
} else {
console.log('3. You will see me if the condition is falsy.');
}
if ('') {
console.log('4. You will see me if the condition is truthy.');
} else {
console.log('4. You will see me if the condition is falsy.');
}
if (``) {
console.log('5. You will see me if the condition is truthy.');
} else {
console.log('5. You will see me if the condition is falsy.');
}
if (null) {
console.log('6. You will see me if the condition is truthy.');
} else {
console.log('6. You will see me if the condition is falsy.');
}
if (undefined) {
console.log('7. You will see me if the condition is truthy.');
} else {
console.log('7. You will see me if the condition is falsy.');
}
if (NaN) {
console.log('8. You will see me if the condition is truthy.');
} else {
console.log('8. You will see me if the condition is falsy.');
}
/* OUTPUT:
1. You will see me if the condition is falsy.
2. You will see me if the condition is falsy.
3. You will see me if the condition is falsy.
4. You will see me if the condition is falsy.
5. You will see me if the condition is falsy.
6. You will see me if the condition is falsy.
7. You will see me if the condition is falsy.
8. You will see me if the condition is falsy.
*/
The code snippet above may look bizarre in JavaScript, but I just wanted to prove that these values are indeed falsy 😅. The conditional statement in every if statement will fail due to the falsy values, causing the else block to run.
Notice that an empty array [] and empty object {} are not on this list. These are considered truthy in JavaScript.
javascript
const emptyArray = [];
const emptyObject = {};
if (emptyArray) {
console.log('1. You will see me if the condition is truthy.');
} else {
console.log('1. You will see me if the condition is falsy.');
}
if (emptyObject) {
console.log('2. You will see me if the condition is truthy.');
} else {
console.log('2. You will see me if the condition is falsy.');
}
/* OUTPUT:
1. You will see me if the condition is truthy.
2. You will see me if the condition is truthy.
*/