Wednesday, January 23, 2019

javascript "if" condition check on undefined variable or property

In Javascript, when using if statement to check a variable's or a property's value is true or false, different result may happen depending whether the variable is declared, assigned or not.

If a javascript variable is not declared, then using if check on the variable will causes unreferenced exception
try
{
    if (someVariable){
         console.log("not get here")
    }
    else{
         console.log("not get here")
    }
}
catch(err){
     console.log("throw reference error: " +err);
}

if the variable is declared, but not defined, then the if check will return false

var someVariable1;
if (someVariable1) {
    console.log("if condition false")
}
else
{
  console.log("Get it here")

}

So for variable check, it is better to check typeof variable to undefined
try
{
    if (typeof someVariable5 == 'undefined'){
         console.log("get here")
    }
    else{
         console.log("not get here")
    }
}
catch(err){
     console.log("not get here: " +err);
}

var someVariable6;
if (typeof someVariable6 == 'undefined') {
    console.log("get here")
}
else
{
  console.log("Not get here")

}



For property, if the base object is undeclared or undefined, then exception will happen

try
{
    if (someVariable2.someProperty){
         console.log("not get here")
    }
    else{
         console.log("not get here")
    }
}
catch(err){
     console.log("throw reference error " + err);
}

var someVariable3;
try{
if (someVariable3.someProperty) {
    console.log("not get here")
}
else
{
  console.log("not get here")
}
}catch (err){
     console.log("throw type error " + err);
}


if the base variable has a value, then if check works

var someVariable4 = {};
if (someVariable4.someProperty) {
    console.log("if condition false")
}
else
{
  console.log("get here")
} 


For property check, first need to check the base variable is not undefined, which means it has a value assigned, and then check the property directly using if condition



try
{
    if (typeof someVariable7 != 'undefined' && (someVariable7.someProperty)){
         console.log("not get here")
    }
    else{
         console.log("get here")
    }
}
catch(err){
     console.log("not throw exception " + err);
}

var someVariable8;
try{
if (typeof someVariable8 != 'undefined' && (someVariable8.someProperty)) {
    console.log("not get here")
}
else
{
  console.log("get here")
}
}catch (err){
     console.log("not throw exception " + err);
}

var someVariable9 = {};
if (typeof someVariable9 != 'undefined'  && (someVariable9.someProperty)) {
    console.log("not get here")
}
else
{
  console.log("get here, property is undefined")

}

No comments:

Post a Comment