KARPACH

WEB DEVELOPER BLOG

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 the var keyword but was never assigned any value.
  2. A variable is declared as a function parameter, but when the function was 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 a variable. Here is an example of a 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 an undefined value
v = some value

The second case is similar and you can use an if statement as in the 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 is when a variable is never declared. If you try to use a such variable you get an exception. If a 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 a third-party API or AJAX requests, always be careful what you consume from a partially unreliable resource.

Posted on January 12, 2012 by