Skip to content Skip to sidebar Skip to footer

Javascript Unassigned Var?

What happens to a variable declared in Javascript, if no initial value was assigned to it? Let's suppose that I declare the variable as below var cancel; Now, does this variable 'c

Solution 1:

undefined is a property of the global object, i.e. it is a variable in global scope. The initial value of undefined is the primitive value undefined.

In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.

A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned.

Since undefined is not a reserved word, it can be used as an identifier (variable name) in any scope other than the global scope.

Example

var x;
if (x === undefined) {
    // these statements execute
}
else {
    // these statements do not execute
}


typeof operator

Alternatively, typeof can be used:

var x;
if (typeof x === 'undefined') {
    // these statements execute
}

One reason to use typeof is that it does not throw an error if the variable has not been defined.

// x has not been defined beforeif (typeof x === 'undefined') { // evaluates to true without errors// these statements execute
}

if(x === undefined){ // throws a ReferenceError

}


void operator

The void operator is a third alternative.

var x;
if (x === void0) {
    // these statements execute
}

// y has not been defined beforeif (y === void0) {
    // throws a ReferenceError (in contrast to `typeof`)
}


Source: MDN - Mozilla Developer Network

Solution 2:

If you just execute the following you will see the alert box with undefined value. Just try yourself in Firebug or chrome developer tool

var cancel;
alert(cancel)

Solution 3:

Undeclared variables or variables without a value have a type of 'undefined'.

It's important to note that unlike some other languages (like PHP, for example) 'undefined' is a Javascript keyword that can be checked against, for example:

if(cancel == undefined) { alert('Cancel is undefined!'); };

You can check for the type of a Javascript variable using the javascript

typeof

command, for example:

var cancel;
var typeOfCancel = typeof cancel; // In this case, undefinedvar cancel = true;
var typeOfCancel = typeof cancel; // In this case, boolean

This can lead to an extra check, when working with javascript, to see if a variable has been set, as in:

if(cancel == undefined || cancel == null || cancel == '') {
    // React to the empty value here
}

You can see this working here: http://jsfiddle.net/7bu84/

Post a Comment for "Javascript Unassigned Var?"