最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Checking for nullundefined in JavaScript - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question asked Dec 5, 2010 at 18:37 Šime VidasŠime Vidas 186k65 gold badges287 silver badges391 bronze badges 2
  • possible duplicate of stackoverflow./questions/801032/null-object-in-javascript – Hps Commented Dec 5, 2010 at 18:43
  • @Hps I searched on SO. This question has never been asked. – Šime Vidas Commented Dec 5, 2010 at 18:46
Add a ment  | 

3 Answers 3

Reset to default 11

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 acmodation 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) { }
发布评论

评论列表(0)

  1. 暂无评论