Last Updated: February 18, 2020
·
972
· boopathi

How do you check undefined ?

How do you check if a variable is undefined in JavaScript ?

Solution 1:

(typeof x === "undefined")

It turns out that, checking x directly instead of passing it to a typeof operator and then doing a string match.

Solution 2:

( x === undefined )

Still, this might fall into the bug where someone redefines undefined to something else.

undefined = 1 // BOOM!

So, the best way to check for undefined is to use the void operator which is defined as

"The void operator evaluates the given expression and then returns undefined."

Solution 3:

(x === void 0)

The void operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired.

Written by Boopathi Rajaa

Recommend
Say Thanks
Update Notifications Off
Respond

2 Responses
Add your response

I heard that undefined is immutable in EcmaScript 5. Turns out it actually means something else than I expected: https://gist.github.com/mzgol/5356300

BTW, lodash.js uses solution 1.

over 1 year ago ·

@analog-nico after checking the gist everything looks fine. #1 and #2 are not really uses of "undefined" but a parameter using a JavaScript built-in object name which is not recommended but possible. You could also use parameters names like window, document or location with similar results.

over 1 year ago ·