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.
At least in the time of writing... No, it does not seem that you can do something like this:
The reason is that you cannot pass an undeclared variable to a function; It raises an error, even in non-strict mode.
The best we can do, is this:
Why?
For example:
When we try to log an
undeclared
variable, it raises an error. Trying to log anundefined
variable does not. We make atry catch
to check for just that.'use strict'
Worth mentioning that adding
'use strict'
in your code verifies that no undeclared variable is present, and raises an error if one is present.Further reading: