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?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With