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?
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.
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.
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".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With