How to check if a variable is undefined versus it is undeclared in javascript?
At least in the time of writing... No, it does not seem that you can do something like this:
var a = undeclared(var) ? 'undeclared' : 'undefined'
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:
var barIsDeclared = true;
try { bar; }
catch (e) {
if (e.name == "ReferenceError") {
barIsDeclared = false;
}
}
console.log(barIsDeclared);
Why?
Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword.
Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global.
For example:
- Undefined:
var a;
undefined
console.log(a) // Success!
- Undeclared:
console.log(myVariable) // ReferenceError: myVariable is not defined
When we try to log an undeclared
variable, it raises an error. Trying to log an undefined
variable does not. We make a try 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.
function define() {
//'use strict' verifies that no undeclared variable is present in our code
'use strict';
x = "Defined";
}
define();
ReferenceError: x is not defined
Further reading:
- Checking if a variable exists in javascript
- What are undeclared and undefined variables in JavaScript?
- JS Interview Question: What’s the difference between a variable that is: null, undefined or undeclared?
- JavaScript check if variable exists (is defined/initialized)
- Strict mode