Šime Vidas
Šime Vidas

Reputation: 185873

Checking for null/undefined in JavaScript

Can this code

if (typeof foo != "undefined" && foo !== null) { }  

be safely refactored into this code?

if (foo != null) { }

Is it the exact same thing? (And if not, how is it different?)

Upvotes: 8

Views: 6072

Answers (3)

PleaseStand
PleaseStand

Reputation: 32052

Variables can actually hold the value undefined, which is the default value if a variable has never been assigned to. So foo != null will work if your variable is declared using var or given a value through assignment, but if it isn't, you will get a ReferenceError. Therefore, the two snippets are not equivalent.

If you can be sure that foo is declared, this is safe and easier to understand than your original second snippet, assuming that nowhere in the code something like undefined = 42 exists:

if(foo !== undefined && foo !== null) { }

Upvotes: 2

Lee
Lee

Reputation: 13542

A simple experiment will answer this question:

if( foo != null ) {
   alert('foo not null');
}

the above example yields a javascript error in many browsers: "ReferenceError: Can't find variable: foo". This is because we've used a variable that has not been previously declared as an argument or var in current scope.

the typeof operator, on the other hand, makes an explicit accommodation for variables that haven't been defined -- it returns 'undefined', so:

if( typeof foo != 'undefined') {
    alert('foo is not defined');
}

works as expected.

So the answer is "no" -- they are not the same thing -- though in some javascript environments they may behave the same way, in other environments your second form will produce errors when foo is not defined.

Upvotes: 2

Daniel Vassallo
Daniel Vassallo

Reputation: 344251

Not really. You'll get thrown a ReferenceError exception in your second example if foo has not been declared.

On the other hand, you can safely check for undefined non-declared variables with the typeof operator.

Upvotes: 11

Related Questions