Last Updated: September 09, 2019
·
654
· elegantmonkey

JavaScript: Is the variable defined?

Sometimes, you may want to check if a variable is already defined e.g. to not override definitions made by other scripts. However, there are many ways to check if a variable is or isn't defined in JavaScript. Here, I'll try to cover some of them.

The first one is checking if the value of the variable is identical to undefined:

var x; // x is declarated, but doesn't has a value i.e. undefined
if (x === undefined) { // True
    // x is undefined
}

This approach only works if the variable is, at least, declarated. If it isn't, a ReferenceError happens. To avoid this, use typeof:

var x;
if (typeof x === "undefined") { // True
    // ...
}
if (typeof y === "undefined") { // True, with y not declarated.
    // ...
}

Another way to check if a variable is declarated is to check on the scope, or, if the variable is global, on the global object.

var x;
if ("x" in this) { // True
    // ...
}

if ("y" in this) { // Nope, but look, no error
    // ...
}

var Klazz = function() {
    this.something = 0;
    if ("something" in this) { // Also true
        // ...
    }
}

As a last note, this, in the global scope, on most browsers, is the same as the window object.

Sources:

Mozilla Developer Network - Undefined

Stack Overflow

1 Response
Add your response

In most cases undefined is not declared variable. If you want to declare empty variable, initialize it with null, not undefined and then just test for condition typeof x == 'undefined'

over 1 year ago ·