How to Check undefined in JavaScript

In JavaScript, three properties, undefined, null, and nan, are confusing at first, but when you study deep, you will know each is different in its own grounds.

What is undefined in JavaScript

The undefined property in JavaScript suggests that a variable has not been assigned a value or not declared at all. The global undefined property describes the primitive value undefined. It is one of JavaScript’s primitive data types.

A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A method returns undefined if a value was not returned.

Javascript check undefined

To check if the value is undefined in JavaScript, use the typeof operator. The typeof operator returns a string indicating the type of the unevaluated operand. Use typeof operator with if condition and compare the value of the variable using undefined, and you will get your result.

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 if the data variable is undefined or not. We have not assigned any value to a data variable previously, so it returns undefined. The undefined comes into a picture when any variable is defined already but has not been assigned any value.

If you want 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 before. In many cases, == can be better because it tests for both null and undefined.

if(typeof never_declared_var === "undefined") // no errors

if(never_declared_var === null) // throws ReferenceError: never_declared_var is not defined

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