Q:

How to check if a variable exists or defined in JavaScript

0

How to check if a variable exists or defined in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the typeof operator

If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.

The most important reason of using the typeof operator is that it does not throw the ReferenceError if the variable has not been declared. Let's take a look at the following example:

<script>
var x;
var y = 10;

if(typeof x !== 'undefined'){
    // this statement will not execute
    alert("Variable x is defined.");
}

if(typeof y !== 'undefined'){
    // this statement will execute
    alert("Variable y is defined.");
}

// Attempt to access an undeclared z variable
if(typeof z !== 'undefined'){
    // this statement will not execute
    alert("Variable z is defined.");
}

/* Throws Uncaught ReferenceError: z is not defined,
and halt the execution of the script */
if(z !== 'undefined'){
    // this statement will not execute
    alert("Variable z is defined.");
}

/* If the following statement runs, it will also
throw the Uncaught ReferenceError: z is not defined */
if(z){
    // this statement will not execute
    alert("Variable z is defined.");
}
</script>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now