left click
left click

Reputation: 894

How to check if a variable is declared in JavaScript?

If I declare variable like this,

let variable;

How to check if the variable is declared?

(If it is initilized, I will do this way..)

if (typeof variable !== 'undefined') { }

Upvotes: 0

Views: 680

Answers (2)

RoastDuck
RoastDuck

Reputation: 122

You can catch ReferenceError to check if the variable is declared or not.

var declared = true;
try{
    theVariable;
}
catch(e) {
    if(e.name == "ReferenceError") {
        declared = false;
    }
}

Upvotes: 3

user886
user886

Reputation: 1197

A variable that is not declared will produce a ReferenceError, so you need a simple try catch:

try {
  if (typeof variable !== 'undefined') { }
} catch(error) {
  //Handle nondeclared
}

Upvotes: 1

Related Questions