The difference between: if ((typeof OA! = 'Undefined') && OA) and if (OA)

What is the difference between: if((typeof OA != 'undefined') && OA )and if(OA)?

The former expression works; the latter quietly stops the execution of the current function.

(maybe a rookie question)

Thank!

+3
source share
3 answers

if(OA)will fail if it OAhas never been determined. typeof OA != 'undefined'checks if exists OA.

var OA;
if(OA){
}

It works.

if(OA){
}

It does not work: OA is not defined.

typeof OA != 'undefined' && OA checks if this is defined before trying to access the variable

+4
source

the compiler will not try to evaluate OA incase of typeof, where, as in it, it tries to evaluate if (OA)

0
source
if ((typeof OA != 'undefined') && OA)

, OA. , .

if(OA)

This assumes that it exists OAand immediately translates it into a logical one and evaluates it.

The second example will throw a javascript exception if the variable OAhas never been declared - the first example avoids this.

See my answer here for a more detailed explanation of several values undefinedin javascript.

0
source

All Articles