1

Possible Duplicate:
variable === undefined vs. typeof variable === “undefined”

Assuming that undefined has not been tampered with, are the following equivalent?

typeof a === 'undefined'

and

a === undefined

?

[The reason I ask is because the author of Parsley.js seems to love writing 'undefined' !== typeof someExpression.]

Community
  • 1
  • 1
Randomblue
  • 112,777
  • 145
  • 353
  • 547
  • 1
    No, they are *not* equivalent. –  Jan 27 '13 at 20:56
  • 1
    Any expression *except* that which consumes a Reference Specification Type (e.g typeof, del, lhs of =) will force variables/properties to be evaluated. It is during this evaluation that a ReferenceError may be raised. –  Jan 27 '13 at 20:59
  • 1
    Thx for having a deep look to Parsley code :) – guillaumepotier Feb 22 '13 at 07:39

2 Answers2

5

These two approaches are almost the same, except one: typeof won't raise ReferenceError: a is not defined in case if a variable was not defined as a variable.

Say, typeof approach is just more fool-proof.

VisioN
  • 143,310
  • 32
  • 282
  • 281
1

Yes they are equivalent if undefined has not been tampered with. The only reason typeof is preferred over direct comparison with undefined is because undefined can be redefined to be anything else like undefined = 5. Also as pointed out by VisioN a can raise a ReferenceError when your not checking in the context of function parameter but rather whether a is defined globally. In order to not get a ReferenceError when comparing directly to undefined in the global context you need to perform:

window.a === undefined
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100