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

前端 未结 24 2219
悲&欢浪女
悲&欢浪女 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:35

    If the purpose of the if statement is to check for null or undefined values before assigning a value to a variable, you can make use of the Nullish Coalescing Operator, is finally available on JavaScript, though browser support is limited. According to the data from caniuse, only 48.34% of browsers are supported (as of April 2020).

    const a = some_variable ?? '';
    

    This will ensure that the variable will be assigned to an empty string (or any other default value) if some_variable is null or undefined.

    This operator is most suited for your use case, as it does not return the default value for other types of falsy value such as 0 and ''.

提交回复
热议问题