Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for null/undefined in JavaScript

Tags:

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?)

like image 438
Šime Vidas Avatar asked Dec 05 '10 18:12

Šime Vidas


3 Answers

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.

like image 85
Daniel Vassallo Avatar answered Sep 24 '22 16:09

Daniel Vassallo


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.

like image 32
Lee Avatar answered Sep 24 '22 16:09

Lee


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) { }
like image 38
PleaseStand Avatar answered Sep 23 '22 16:09

PleaseStand