Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking for undefined in javascript-- should I use typeof or not?

I'm a bit confused about how best to check if a variable is undefined or not in javascript. I've been doing it like this:

myVar === undefined;

But is it better in all cases to use typeof instead?

typeof myVar === undefined;

And what about the use of undefined vs "undefined", which I've also seen?

like image 458
larryq Avatar asked Feb 26 '13 16:02

larryq


People also ask

Should you use undefined in JavaScript?

TLDR; Don't use the undefined primitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference.

Can we check undefined in JavaScript?

When using x === undefined , JavaScript checks if x is a declared variable that is strictly equal to undefined . If you want to check if x is strictly equal to undefined regardless of whether is has been declared or not, you should use typeof x === 'undefined' .

How do you handle undefined variables in JavaScript?

myVariable is declared and not yet assigned with a value. Accessing the variable evaluates to undefined . An efficient approach to solve the troubles of uninitialized variables is whenever possible assign an initial value. The less the variable exists in an uninitialized state, the better.

Why typeof undefined is undefined?

Here the assigned variables don't have any value but the variable exists. Here the type of variable is undefined. If you assigned a value(var geeks === undefined ) it will show, if not it will also show undefined but in different meaning. Here the undefined is the typeof undefined.


2 Answers

This is the best way to check -- totally foolproof:

typeof myVar === "undefined"

This is OK, but it could fail if someone unhelpfully overwrote the global undefined value:

myVar === undefined;

It has to be said that ECMAScript 5 specifies that undefined is read-only, so the above will always be safe in any browser that conforms.

This will never work because it ends up comparing "undefined" === undefined (different types):

typeof myVar === undefined;
like image 143
Jon Avatar answered Oct 02 '22 23:10

Jon


This test would always work as expected:

typeof a === 'undefined'

Since the value of undefined can be changed, tests like these aren't always reliable:

a = {}
a.b === undefined

In those cases you could test against void 0 instead:

a.b === void 0
// true

However, this won't work for single variable tests:

a === void 0 // <-- error: cannot find 'a'

You could work around that by testing against window.a, but the first method should be preferred.

like image 22
Ja͢ck Avatar answered Sep 30 '22 23:09

Ja͢ck