Something that's useful to keep in mind is that Javascript is dynamically typed, even if it looks like it's just variables. There are a handful of types in JS, and Undefined (with caps) is one, and the only value it can hold is undefined
. Think of it like saying you have the Number type and it only accepts 42. This is important to know because JS engines have to observe spec.
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.
There is a lot of variation in application code, but you can know that variables that have not been assigned are of type Undefined with value undefined
and not something else. Next to Undefined is Null, which has a single value, null
. Null, unlike Undefined, needs to be assigned.
In the spec you'll also the find the table for the result you get for each variable type.
You'll notice that Undefined has its own return value, as well as Boolean, but Null returns "object"
, which is reported to be a mistake in the original spec that we can't get rid of.
With types out of the way, we get to Boolean coercion, which is how if statements work out the condition. The spec has a table of cases that define when a value should be coerced into true
or false
.
You'll see that an if
clause receives the Undefined type, it returns false
. The same happens with Null. There are a few other cases that can also return false even if they are not Undefined or Null.
- The Number type with values
0
, -0
, NaN
- The String type with length 0 (
""
)
- The BigInt type with value 0
As others have already answered, applications of the spec come in a few different places. The reasons as for why typeof
exists and there is an overlap with the falsey evaluation arise from how the JS engines handle values and perform coercion into Boolean.