How to check ‘undefined’ value in jQuery

How to check ‘undefined’ value in jQuery

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
}

Solutions/Answers:

Solution 1:

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.

Solution 2:

In this case you can use a === undefined comparison: if(val === undefined)

This works because val always exists (it’s a function argument).

Related:  How to encode a string in JavaScript for displaying in HTML? [duplicate]

If you wanted to test an arbitrary variable that is not an argument, i.e. might not be defined at all, you’d have to use if(typeof val === 'undefined') to avoid an exception in case val didn’t exist.

Solution 3:

Note that typeof always returns a string, and doesn’t generate an error if the variable doesn’t exist at all.

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

Solution 4:

I know I am late to answer the function but jquery have a in build function to do this

if(jQuery.type(val) === "undefined"){
    //Some code goes here
}

Refer jquery API document of jquery.type https://api.jquery.com/jQuery.type/ for the same.

Solution 5:

You can use shorthand technique to check whether it is undefined or null

 function A(val)
 {
   if(val || "") 
   //do this
 else
 //do this
 }

hope this will help you

Solution 6:

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