variable === undefined vs. typeof variable === "undefined"

Patrick McElhaney picture Patrick McElhaney · Jan 18, 2011 · Viewed 85.4k times · Source

The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.

  • Global Variables: typeof variable === "undefined"
  • Local Variables: variable === undefined
  • Properties: object.prop === undefined

Why does jQuery use one approach for global variables and another for locals and properties?

Answer

Linus Kleen picture Linus Kleen · Jan 18, 2011

For undeclared variables, typeof foo will return the string literal "undefined", whereas the identity check foo === undefined would trigger the error "foo is not defined".

For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.