Javascript undefined type has only one value, which is the special value undefined
.
When a variable is declared using var
or let
but not initialized, it is assigned the value of undefined
:
let message; console.log(message == undefined); // true
In this example, the variable message
is declared without initializing it.
When compared with the literal value of undefined
, the two are equal.
This example is identical to the following:
let message = undefined; console.log(message == undefined); // true
Here the variable message
is initialized to be undefined
.
By default, any uninitialized variable gets the value of undefined
.
A variable containing the value of undefined
is different from a variable that hasn't been defined.
Consider the following:
let message; // this variable is declared but has a value of undefined console.log(message); // "undefined" console.log(age); // causes an error
In this example, the first console.log displays the variable message, which is "undefined".
In the second console.log, an undeclared variable called age
is passed into the console.log()
function.
It causes an error because the variable hasn't been declared.
We can call typeof
on an undeclared variable.
Calling delete
on an undeclared variable won't cause an error.
typeof aVariable; //undefined delete aVariable; //throw error in strict mode
It throws an error in strict mode.
The typeof
operator returns "undefined" on an uninitialized variable.
It also returns "undefined" when called on an undeclared variable.
let message; // this variable is declared but has a value of undefined console.log(typeof message); // "undefined" console.log(typeof age); // "undefined"
It is advisable to always initialize variables.
That way, when typeof returns "undefined", we know that it's because a given variable hasn't been declared rather than was not initialized.