How to check if a javascript variable is undefined?

How to check if a javascript variable is undefined? This is actually a tricky question. There are three cases:

  1. A variable is declared using var keyword, but were never assigned any value.
  2. A variable is declared as function parameter, but when function were invoked parameter was not supplied.
  3. A variable is never declared or assigned a value and you are trying to access it.

First two cases lead to undefined value of variable. Here is an example of first case:

var v; // Value not defined
if (v) {
    console.log("v=" + v);
}
else {
    console.log("v has undefined value");
}
v = "some value";
if (v) {
    console.log("v = " + v);
}


Output:
v has undefined value
v = some value

The second case is similar and you can use if statement as in above code or:

function Add(p1, p2) {
    p1 = p1 || 0; // set value to 0 if value is undefined
    p2 = p2 || 0; // set value to 0 if value is undefined
    return p1 + p2; // would always work
}
 
console.log(Add(1, 2));
console.log(Add(1));
console.log(Add());


Output:
3
1
0

The third case when a variable is never declared. If you try to use such variable you get exception. If statement or default value assignment won't help.

if(typeof neverDeclared == "undefined") {
    console.log("There is something really wrong!");
}


You would ask, what kind of sick people try to use a variable that was never declared or assigned a value? However I bet this is one of the most frequent javascript exceptions. Yes, simple variables are usually declared, but exception usually happens when you try to pass complex object with undeclared property. Javascript objects can be easily extended with additional properties and this comes at price of frequent undefined variable exceptions. Let me give you an example:

var obj = { FirstName: "Viktar", LastName: "Karpach" };
console.log(obj.FirstName);
console.log(obj.LastName);
console.log(obj.City); // Will give exception
 
var obj = { FirstName: "Viktar", LastName: "Karpach" };
obj.City = "Chicago";
console.log(obj.City); // Works!
 
if (typeof obj.State == "undefined") {
    console.log("State is undefined.");
}

Undefined variable exception very often happens when you try to consume objects received from third party API or from AJAX requests, always be careful what you consume from partially unreliable resource.


Posted on Thursday, January 12, 2012 by | Add Comment

New Comment

Your Name:
Email (for internal use only):
Comment:
 
Code above:

Categories

Recent Tweets

  • Simon Ince's Blog: Hierarchies with HierarchyID in SQL 2008 http://t.co/xSDwiF6rRS.
  • Visual Studio 2010 WAS painfully slow - CodeProject http://t.co/Usba1x6CZy

Valid HTML5