Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a variable exist in JavaScript?

Tags:

I am not asking if the variable is undefined or if it is null. I want to check if the variable exists or not. Is this possible?

like image 764
scatman Avatar asked May 04 '11 06:05

scatman


People also ask

How do you check if a variable is exist or not in JavaScript?

JavaScript has a built-in function to check whether a variable is defined/initialized or undefined. Note: The typeof operator will check whether a variable is defined or not. The typeof operator doesn't throw a ReferenceError exception when it is used with an undeclared variable.

How do you check if a variable exists?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do you check if a variable has a value?

To check if a variable is not given a value, you would only need to check against undefined and null. This is assuming 0 , "" , and objects(even empty object and array) are valid "values".

How do you check if a variable is undefined in JS?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.


1 Answers

The typeof techniques don't work because they don't distinguish between when a variable has not been declared at all and when a variable has been declared but not assigned a value, or declared and set equal to undefined.

But if you try to use a variable that hasn't been declared in an if condition (or on the right-hand side of an assignment) you get an error. So this should work:

var exists = true; try {     if (someVar)         exists = true; } catch(e) { exists = false; } if (exists)    // do something - exists only == true if someVar has been declared somewhere. 
like image 108
nnnnnn Avatar answered Sep 23 '22 18:09

nnnnnn