How to Check for undefined in JavaScript

To check undefined in JavaScript, you can use the typeof operator and compare it directly to undefined using the triple equals (===) operator.

Example

let data = undefined;

if (typeof (data) === undefined) {
 console.log('Yes in fact it is undefined');
}

Output

Yes in fact it is undefined

JavaScript typeof is an inbuilt operator that returns the string, indicating a type of the unevaluated operand.  The operator returns a data type of its operand as a string.

Using the void operator in JavaScript

The void operator checks the given expression and then returns undefined. You can use a void operator to get the value of undefined. This will work even if the global window.undefined value has been overwritten.

See the following code and how to use the void operator to check for undefined.

let data = undefined;

if (data === void(0)) {
  console.log('Yes in fact it is undefined');
}

Output

Yes in fact it is undefined

The zero(0) in the above code example doesn’t have any special meaning, and you could use 1 or function(){}. void(anything) will always evaluate as undefined.

When not to use void or typeof

Avoid using void(0) or typeof data === “undefined” verbatim in code. These expressions aren’t self-explanatory and should be wrapped in a user-defined function like isUndefined() function below.

let data = undefined

const isUndefined = (value) => {
  let undefined = void (0);
  return value === undefined;
}

console.log(isUndefined(data));

Output

true

From the output, you can see that the data is undefined, and the function returns true. If you want to use void(), then this is how you can use it, but again I am not recommending this solution.

Conclusion

To check if a variable is undefined in JavaScript, you can use the triple-equals operator (===) with the typeof() operator.

See also

JavaScript ternary operator

JavaScript instanceof operator

JavaScript delete operator

JavaScript rest operator

JavaScript spread operator

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.