Falsy Values
JavaScript has a surprisingly large set of falsy values, shown in See Table A-1.
Table A-1. The many falsy values of JavaScript
Value |
Type |
---|---|
|
Number |
|
Number |
|
String |
|
Boolean |
|
Object |
|
Undefined |
These values are all falsy, but they are not interchangeable. For example, this is the wrong way to determine if an object is missing a member:
value = myObject[name]; if (value == null) { alert(name + ' not found.'); }
undefined
is the value of missing members, but
the snippet is testing for null
. It is using the
==
operator (see Appendix B), which does type coercion, instead of the more reliable ===
operator. Sometimes those two errors cancel each other out.
Sometimes they don't.
undefined
and NaN
are not constants. They are global variables, and you can change
their values. That should not be possible, and yet it is. Don't do it.
Get JavaScript: The Good Parts now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.