简体   繁体   中英

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

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.

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.

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) { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM