How to Check for ‘undefined’ Value in jQuery

javascriptjqueryundefined

Possible Duplicate:
Detecting an undefined object property in JavaScript
javascript undefined compare

How we can add a check for an undefined variable, like:

function A(val) {
  if (val == undefined) 
    // do this
  else
    // do this
}

Best Answer

JQuery library was developed specifically to simplify and to unify certain JavaScript functionality.

However if you need to check a variable against undefined value, there is no need to invent any special method, since JavaScript has a typeof operator, which is simple, fast and cross-platform:

if (typeof value === "undefined") {
    // ...
}

It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to if (value === undefined) { ... }, is that typeof will never raise an exception in case if variable value does not exist.

Related Question