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

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

    In order to understand, Let's analyze what will be the value return by the Javascript Engine when converting undefined , null and ''(An empty string also). You can directly check the same on your developer console.

    You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code like below.

    if (a === undefined || a === null || a==='') {
        console.log("Nothing");
    } else {
        console.log("Something");
    }
    

    Also I want to point out one more thing.

    What will be the result of Boolean(0)?

    Of course false. This will create a bug in your code when 0 is a valid value in your expected result. So please make sure you check for this when you write the code.

提交回复
热议问题