How to Check for undefined in JavaScript

To check for an undefined value in JavaScript, you can use the “typeof operator”. The typeof operator returns a string indicating the type of the unevaluated operand.

if (typeof data === "undefined") {
 console.log("data is undefined")
} else {
 console.log("data is defined")
}

Output

data is undefined

In this example, we are checking whether the data variable is undefined. We have not assigned any value to a data variable previously, so it returns undefined.

The undefined comes into the picture when any variable is defined already but has not been assigned any value.

To check if the value of a variable should not be undefined, use the following code.

let data

if (typeof data != "undefined") {
 console.log("data is defined")
} else {
 console.log("data is undefined")
}

Output

data is undefined

Strict equality and undefined

Use undefined and strict equality and inequality operators to define whether a variable has a value.

let data

if (typeof data === "undefined") {
 console.log("data is undefined")
} else {
 console.log("data is defined")
}

Output

data is undefined

In this example code, the variable data is not initialized, and the if statement evaluates to true.

typeof !== “undefined” vs. != null

The typeof operator is relatively safe as it provides the identifier never to have been declared. However, in many cases, == can be better because it tests for both null and undefined.

if(typeof never_declared_var === "undefined")

if(never_declared_var === null)

If the variable is declared using either the var keyword as a function argument or a global variable, use the following code.

if (typeof something != "undefined") {
    // ...
}

That is it for this tutorial.

Leave a Comment