Appearance
Truthy
JavaScript automatically converts values to booleans in conditional contexts like if statements or && operations. This implicit conversion follows specific rules that can sometimes be surprising, especially for developers coming from other languages. Using strict equality (===) instead of loose equality (==) helps limit these surprises by preventing automatic type conversion.
Truthy and Falsy
Values are automatically converted to true or false based on these rules:
These falsy values, all convert to false:
js
false // boolean false
0 // number zero
"" // empty string
null // null
undefined // undefined
NaN // Not a NumberEverything else is truthy, here are some examples:
js
if ("hello") { // true - non-empty string
console.log("truthy!");
}
if (42) { // true - any non-zero number
console.log("truthy!");
}
if ([]) { // true - empty array is truthy!
console.log("truthy!");
}
if ({}) { // true - empty object is truthy!
console.log("truthy!");
}⚠️ Be careful! Empty arrays and objects are truthy, which can be surprising since in Python an empty list
[]is false. In TypeScript, you'll usually check specific conditions instead of relying on truthy/falsy conversion.
Equality vs Strict Equality
The loose equality operator (==) also performs type conversion, leading to some surprising results:
js
0 == "" // true! (both are falsey)
1 == "1" // true! (string converted to number)Strict equality (===) doesn't convert types
js
0 === "" // false (number vs string)
1 === "1" // false (number vs string)🛑 Always use strict equality (
===) to avoid unexpected type conversion.
External Resources