Truthy and Falsy Values
The following values are always falsy:
- 0 (zero)
- "" (empty string)
- NaN (a special Number value meaning Not-a-Number!)
All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.
var a = !!(0); // variable is set to false
var b = !!("0"); // true
Comparing Falsy Values
Falsy values follow some slightly odd comparison rules which can lead to errors in program logic.
The falsy values false, 0 (zero), and "" (empty string) are all equivalent and can be compared against each other:
var c = (false == 0); // true
var d = (false == ""); // true
var e = (0 == ""); // true
The falsy values null and undefined are not equivalent to anything except themselves:
var f = (null == false); // false
var g = (null == null); // true
var h = (undefined == undefined); // true
var i = (undefined == null); // true
Finally, the falsy value NaN is not equivalent to anything — including NaN!
var j = (NaN == null); // false
var k = (NaN == NaN); // false
You should also be aware that
isNaN() can be used to evaluate whether a value is NaN or not.
If in doubt…
Use strict equal (===) and strict not equal (!==) in situations where truthy or falsy values could lead to logic errors. These operators ensure that the objects are compared by type and by value.
var l = (false == 0); // true
var m = (false === 0); // false