0

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') { }

2 Answers 2

3

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think you mean declared = false; in the catch.
Also, last line, ) should be }. minor, but key.
1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.