[Solved-5 Solutions] JavaScript check if variable exists (is defined/initialized) - javascript Tutorial



Problem:

How to check if a variable exists or defined in JavaScript ?

Solution 1:

This solution to check the existence of variable

<html>
   <body>
      <script>
         var myVar = 10;
         if(myVar !== undefined && myVar !== null) {
            document.write("Exists Variable");
         }
      </script>
   </body>

Read Also

Variable Scope

Solution 2:

We can use typeof operator to check the variable is defined or not.

if (typeof variable !== 'undefined') {
    // the variable is defined
}

Solution 3:

You can use this code:

if (typeof variable === 'undefined') {
    // variable is undefined
}

  • The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
  • Note that typeof null will be return as "object".
  • To avoid the mistake of initializing a variable to null, we can use like this:
if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null

Solution 4:

In JavaScript, a variable can be defined, but hold the value undefined.

if (typeof v === "undefined") {
   // no variable "v" is defined in the current scope
   // *or* some variable v exists and has been assigned the value undefined
} else {
   // some variable (global or local) "v" is defined in the current scope
   // *and* it contains a value other than undefined
}

The following example has simpler semantics, which makes it easier to describe code's behavior.

if ("v" in window) {
   // global variable v is defined
} else {
   // global variable v is not defined
}

Where window is a name for the global object

Solution 5:

This solution gives if a variable exists and has been initialized.

var setOrNot = typeof variable !== typeof undefined;

It is most commonly used in combination with a ternary operator to set a default as certain variable has not been initialized :

var dark = typeof darkColor !== typeof undefined ? darkColor : "black";


Related Searches to JavaScript check if variable exists (is defined/initialized) - javascript tutorial