JavaScript is very flexible about the types of values it requires. If JavaScript wants a boolean, it will convert whatever value you give it to a boolean.
Some values (“truthy” values) convert to true and others (“falsy” values) convert to false.
The following values convert to, and therefore work like, false:
- undefined
- null
- 0
- -0
- NaN
- "" // the empty string
All other values, including all objects (and arrays) convert to, and work like, true.
As an example, suppose that the variable o
either holds an object or the value null
. You can test explicitly to see if o is non-null with an if statement like this:
if (o !== null){
....
}
The strict not-equal operator !==
compares o
to null
and evaluates to either true or false. But you can omit the comparison and instead rely on the fact that null
is falsy and objects are truthy:
if (o){
....
}
In the first case, the body of the if will be executed only if o
is not null
. So the code block will execute even if o is set to undefined
.
The second case is less strict: it will execute the body of the if only if o
is not false
or any falsy value (such as null
or undefined
). Which if statement is appropriate for your program really depends on what values you expect to be assigned to o
. If you need to distinguish null
from 0
and "", then you should use an explicit comparison.