I know that to find if a variable is undeclared in javascript, I can use if (typeof variable === 'undefined')
. If I declare a variable as undefined (var variable = undefined
), the if statement still returns true. Is it possible, in JavaScript, to find the difference between undeclared variables and variables with a value of undefined? I know that they are similar, but doing const variable = undefined
and then variable = "something else"
will throw an error, so they must be different.
const variable = undefined
if (typeof variable === 'undefined') {
console.log('"variable" is undefined')
}
if (typeof undeclaredVariable === 'undefined') {
console.log('"undeclaredVariable" is undefined')
}
I wouldn't like to use a try catch block because I want to be able to assign another constant based on this. I would like a solution like this: const isVariableDeclared = variable === undeclared
, except undeclared
does not exist in javascript. I know I can use let with a try catch block but am looking for something more elegant.
undefinedVariable
in your example is better described as undeclared rather than undefined. You can tell these, in a sense, because any reference to them except for thetypeof
operator will throw aReferenceError
. – Succotashundefined
. – Miliariawindow.hasOwnProperty("variableName")
). That only works for variables declared with var, however. You should promote that to an answer, though. – Embrangleconst object = {};
and set properties on it, e.g.object.var1 = "something";
Checking whethervar1
andvar2
exist looks like this:object.hasOwnProperty("var1")
andobject.hasOwnProperty("var2")
, which yieldtrue
andfalse
, respectively. – Facient