22 Aralık 2008 Pazartesi

typeof and undefined in Javascript

For declared but unassigned variables (not object attributes),
      x==undefined yields true
      typeof x=="undefined" yields true, too.
BUT
For undeclared variables the former throws error,
whereas the latter returns true.

So,

  • If we don' t guarantee that the variable has been declared, it is good to use typeof x=="undefined" to test whether the variable has been declared or not.
  • If we know that the varible has been declared, it is good to use x==undefined to catch our typing errors.

Object attributes could be thought as members of hashmaps like below
      x.name === x["name"]
So, for undeclared x.name, x.name == undefined won' t throw error, it will return true.

Hiç yorum yok: