How to check for an undefined or null variable in JavaScript?

前端 未结 24 2208
悲&欢浪女
悲&欢浪女 2020-11-22 15:55

We are frequently using the following code pattern in our JavaScript code

if (typeof(some_variable) != \'undefined\' && some_variable != null)
{
             


        
24条回答
  •  爱一瞬间的悲伤
    2020-11-22 16:31

    In newer JavaScript standards like ES5 and ES6 you can just say

    > Boolean(0) //false
    > Boolean(null)  //false
    > Boolean(undefined) //false
    

    all return false, which is similar to Python's check of empty variables. So if you want to write conditional logic around a variable, just say

    if (Boolean(myvar)){
       // Do something
    }
    

    here "null" or "empty string" or "undefined" will be handled efficiently.

提交回复
热议问题