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.