How to check for an undefined or null variable in

2018-12-31 21:14发布

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

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

Is there a less verbose way of checking that has the same effect?

According to some forums and literature saying simply the following should have the same effect.

if (some_variable)
{
    // Do something with some_variable
}

Unfortunately, Firebug evaluates such a statement as error on runtime when some_variable is undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?

15条回答
其实,你不懂
2楼-- · 2018-12-31 21:48

You have to differentiate between two cases:

  1. Undefined variables , like foo. You'll get an error if you access an undefined variable in any context other than typeof.

    if(typeof someUndefVar == whatever) // works
    
    if(someUndefVar) // throws error  
    

    So, for variables, the typeof check is a must. On the other side, it's only rarely needed - you usually know if your variables are defined or not.

  2. Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about 0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact:

    value = obj.prop || defaultValue
    

    which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue".

    Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead

    value = ('prop' in obj) ? obj.prop : defaultValue
    
查看更多
其实,你不懂
3楼-- · 2018-12-31 21:54

If you try and reference an undeclared variable, an error will be thrown in all JavaScript implementations.

Properties of objects aren't subject to the same conditions. If an object property hasn't been defined, an error won't be thrown if you try and access it. So in this situation you could shorten:

 if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)

to

if (myObj.some_property != null)

With this in mind, and the fact that global variables are accessible as properties of the global object (window in the case of a browser), you can use the following for global variables:

if (window.some_variable != null) {
    // Do something with some_variable
}

In local scopes, it always useful to make sure variables are declared at the top of your code block, this will save on recurring uses of typeof.

查看更多
明月照影归
4楼-- · 2018-12-31 21:54

You must define a function of this form:

validate = function(some_variable){
    return(typeof(some_variable) != 'undefined' && some_variable != null)
}
查看更多
余欢
5楼-- · 2018-12-31 21:56

Open the Developer tools in your browser and just try the code shown in the below image.

Img1 Img2

查看更多
余生无你
6楼-- · 2018-12-31 21:56

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.

enter image description here

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.

查看更多
若你有天会懂
7楼-- · 2018-12-31 21:56

Both values can be easily distinguished by using the strict comparison operator:

Working example at:

http://www.thesstech.com/tryme?filename=nullandundefined

Sample Code:

function compare(){
    var a = null; //variable assigned null value
    var b;  // undefined
    if (a === b){
        document.write("a and b have same datatype.");
    }
    else{
        document.write("a and b have different datatype.");
    }   
}
查看更多
登录 后发表回答