3

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

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

(maybe a rookie question)

Thanks!

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 2
    Could you provide some more context? Both statements are essentially the same, but the second one will fail if `OA` was not even declared (i.e. `var OA;`). You should never be in the second situation, always declare variables (if they are not names of function parameters). – Felix Kling Apr 17 '12 at 17:12
  • 1
    @FelixKling: I think that's the issue here. – gen_Eric Apr 17 '12 at 17:13
  • 1
    @Rocket: Probably... it just seems odd... guess I haven't seen such code in a while ;) And using JSHint really helps too... – Felix Kling Apr 17 '12 at 17:14
  • @FelixKling it is possible that OA is not existent. One thing I don't understand is "fail": is it a bug, or code goes to else branch? – user1279175 Apr 17 '12 at 19:11

3 Answers3

4

if(OA) will fail if OA was never defined. typeof OA != 'undefined' checks if OA is defined.

var OA;
if(OA){
}

This works.

if(OA){
}

This doesn't work: OA is not defined.

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

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 1
    +1, it's probably worth noting that `undefined` is false-y and your first example is not checking `null`, it's checking against `undefined`. People seem to get that confused. Not defined is not the same as the type `undefined`. – Marc Apr 17 '12 at 17:16
0

compiler wont try to evaluate OA incase of typeof where as in it tries to evaluate in if(OA)

Amareswar
  • 2,048
  • 1
  • 20
  • 36
0
if ((typeof OA != 'undefined') && OA)

This will first check if the variable OA is defined. If it is, it will then be cast to a boolean and evaluated.

if(OA)

This assumes OA exists and immediately casts it to a boolean and evaluates it.

The second example will throw a javascript exception if the variable OA has never been declared - the first example avoids that.

See my answer here for more explanation on the multiple meanings of undefined in javascript.

Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • Have double checked with try{}catch(){} to find out: ReferenceError: OA is not defined. So, "not defined", which may cause run-time exception, is not "undefined", which is considered as falsy in boolean operations. Clearly I am a rookie, but why is there the subtle difference? – user1279175 Apr 17 '12 at 19:21
  • http://stackoverflow.com/questions/10098816/is-variable-set-defined-issue/10099267#10099267 – jbabey Apr 17 '12 at 19:22