Reputation: 2485
I have the following code:
simpleExample.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple example</title>
</head>
<body>
Open the Console.
<script src="js/simpleExampleJS.js"></script>
</body>
</html>
js/simpleExampleJS.js
:
MyObject = {
COMPUTER_GREETING: "Hello World!",
hello: function() {
console.log(MyObject.COMPUTER_GREETING);
}
};
checkSomeGlobal = function() {
if(someGlobal === undefined) {
console.log("someGlobal is undefined & handled without an error.");
} else {
console.log("someGlobal is defined.");
}
};
MyObject.hello();
checkSomeGlobal();
When I run this, I get:
Hello World!
Uncaught ReferenceError: someGlobal is not defined
at checkSomeGlobal (simpleExampleJS.js:9)
at simpleExampleJS.js:17
(The first line of output generally indicates that the code is loading and running).
MDN indicates that a potentially undefined variable can be used as the left-hand-size of a strict equal/non-equal comparison. Yet when checking if(someGlobal === undefined)
that line of code produces an error because the variable is undefined, instead of making the comparison evaluate to true
. How can I check for and handle this undefined variable case without an error?
Upvotes: 6
Views: 14566
Reputation: 887817
That error is saying that there is no such variable (it was never declared), not that its value is undefined
.
To check whether a variable exists, you can write typeof someGlobal
, as in:
if (typeof someGlobal === "undefined")
Upvotes: 10