Undefined is a variable in global scope. A variable that has not been assigned any value is referred as undefined.
You can check for undefined in various ways.Here are some ways to check :-
Checking via Strict equality(===)
var a;
if(a=== undefined)
{
// these statements execute
}
In the above code, the variable a is not defined, and the if statement evaluates to true.
Checking via typeof operator
var a;
if(typeof a === 'undefined')
{
// these statements execute
}
Typeof operator also works for undeclared variables,i.e,it does not throw error even if the variable is not declared.
// a has not been declared before
if (typeof a === 'undefined') { // evaluates to true without errors
// these statements execute
}
if(a === undefined){ // throws a ReferenceError
}
Checking via Void operator
var a;
if (a === void 0) {
// these statements execute
}
In Javascript void works as an operator,it takes an operand,it has nothing to do with the results and returns undefined.
We should avoid using void because it always evaluates to undefined.
0 Comment(s)