In JavaScript, when you declare a variable and do not assign any value to it, then JavaScript assigns undefined
to that variable.
There are two ways to determine if a variable is undefined in JavaScript:
1) The typeof
operator returns "undefined"
when a variable has an undefined
value. You can use the value returned by the typeof
operator in an if statement to check whether a variable is undefined or not.
let x; console.log(typeof x); if(typeof x === "undefined"){ console.log("Variable x is not initialized."); }else{ console.log(`The value of x is ${x}.`); }
Output
"undefined" Variable x is not initialized.
2) You can directly use a strict equality operator (===) to check if a variable is undefined or not.
let x; if(x === undefined){ console.log("Variable x has an undefined value."); }else{ console.log(`The value of x is ${x}.`); }
Output
Variable x has an undefined value.
It is important to note that you should not use the equality operator (==) because it returns true
if null
is tested against an undefined
value.
console.log(null == undefined); //true
null
is used to show that the variable does not have any object value. It is one of the primitive data types in JavaScript. In simple terms, null also represents an absence of value.
The simplest way to check if a variable is null is to use a strict equality operator (===) inside the if statement.
let x = null; if(x === null){ console.log("Variable x is null."); }else{ console.log("Variable x is not null."); }
Output
Variable x is null.
It is recommended that you should not use the typeof
operator for checking if a variable is null because the typeof operator returns "object"
for the variable that has a null
value. The typeof operator also returns "object"
for reference type variables.
let x = null; let pdt = { name: "Amazon Alexa" }; console.log(typeof x); //object console.log(typeof pdt); //object
In this example, you can see that the typeof
operator has returned "object"
on the pdt
variable.