Truthy/falsy values
Definition
In JavaScript, any value can be coerced to a logical type (boolean).
- If after coercion it becomes
true-> it is a truthy value. - If it becomes
false-> it is a falsy value.
Easy to check:
javascript
Boolean(value) // returns true or false
!!value // short equivalentList of all falsy values (8 total)
| Value | Description |
|---|---|
false | false |
0 | the number zero |
-0 | negative zero |
0n | BigInt zero |
"" | empty string |
null | "nothing" |
undefined | undefined |
NaN | result of invalid numeric operations |
Everything else in JavaScript is truthy.
Falsy examples
javascript
Boolean(false); // false
Boolean(0); // false
Boolean(''); // false
Boolean(null); // false
Boolean(undefined); // false
Boolean(NaN); // falseTruthy examples
javascript
Boolean(true); // true
Boolean(1); // true
Boolean('0'); // true (string, not empty)
Boolean('false'); // true (also a string)
Boolean([]); // true (an empty array is still truthy)
Boolean({}); // true (empty object)
Boolean(function(){});// true (function)Example in an if condition
javascript
if ('hello') {
console.log('Runs');
}
if (0) {
console.log('Does not run');
}Because
'hello'-> truthy, and0-> falsy.
Example with the && operator
javascript
console.log(true && 'JS'); // "JS" (both truthy)
console.log(false && 'JS'); // false (falsy stops it)Example with the || operator
javascript
console.log('' || 'default'); // "default"
console.log('Hi' || 'default'); // "Hi"
||returns the first truthy value.
Example with double negation !!
javascript
!!'text' // true
!!0 // false
!![] // true
!!null // falseImportant: truthy is not "logically true" in the mathematical sense
JS does not "compare", it coerces values to boolean.
javascript
'false' == true // false
!!'false' // true
'false'is a string (truthy), but when compared totrue, different logic applies (types are coerced first).
Summary
| Type | Examples | Boolean value |
|---|---|---|
| Falsy | false, 0, -0, 0n, "", null, undefined, NaN | false |
| Truthy | '0', ' ', 'false', [], {}, function(){} | true |
In short
Truthy - "behaves like
true" Falsy - "behaves likefalse"
Check:
javascript
if (value) {
// runs if value is truthy
} else {
// if value is falsy
}Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.