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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Is there a standard function to check for null, undefined, or blank variables in JavaScript?相关的知识,希望对你有一定的参考价值。

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?的主要内容,如果未能解决你的问题,请参考以下文章

UVA10462:Is There A Second Way Left? (判断次小生成树)

npm报错This is probably not a problem with npm. There is likely additional logging

Spirng 循环依赖报错:Is there an unresolvable circular reference?

人工智能有简单的算法吗?Appendix: Is there a simple algorithm for intelligence?

Other关于There is a cycle in the hierarchy!

YES, There is No such thing as a free lunch