Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError (not defined) when checking === undefined

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?

like image 685
WBT Avatar asked Mar 06 '23 12:03

WBT


1 Answers

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")
like image 51
SLaks Avatar answered Mar 23 '23 21:03

SLaks