Search code examples
javascriptjqueryundefined

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


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?


Solution

  • For undeclared variables, typeof foo will return the string "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.