typeof null
being object is an early mistake - when they tried correcting it in a Chrome nightly (to typeof null === "null"
) too many things relied on the current behavior and too much code broke.
JavaScript objects that are not set to normal values generally have three states:
- Undeclared.
- Undefined.
- Explicitly nothing.
Undeclared
For example - this case:
y++; //I did not declare y before, this causes a reference error
y === 'undefined'; //still a reference error
typeof y; //'undefined', since typeof is an operator and not a function.
Basically, an undeclared variable is in the state 'the script does not know this variable'.
Undefined
This means that the the runtime 'knows this variable' but it wasn't set to anything yet. Or, as the language specification puts this:
undefined value - primitive value used when a variable has not been assigned a value.
For example:
var y; //y is undefined
y === undefined; //true, y defined the line above
typeof y; //undefined, but this is redundant, just do `=== undefined`
(function(x){ /* x is undefined here as it was set to nothing*/})()
Explicitly nothing
When you have something that is supposed to have a value but you want to declare that it is nothing. Or, as the language specification puts this:
null value - primitive value that represents the intentional absence of any object value.
For example, document.getElementById("foo");
returns null
if the element with the given ID is not in the DOM to indicate explicitly nothing was returned. Constrast this with functions that have no return statements so they return undefined
which is the default.