码迷,mamicode.com
首页 > 编程语言 > 详细

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

时间:2017-04-25 00:36:55      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:als   tor   define   res   .com   logs   stack   blog   typeof   

You can just check if the variable has a truthy value or not. That means

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specificationat the ToBoolean section.

Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if( typeof foo !== ‘undefined‘ ) {
    // foo could get resolved and it‘s defined
}

If you can be sure that a variable is declared at least, you should directly check if it has a truthyvalue like shown above.

Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html

 

http://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in/5515349#5515349

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

标签:als   tor   define   res   .com   logs   stack   blog   typeof   

原文地址:http://www.cnblogs.com/chengdabelief/p/6759679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!