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

13,108

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

Share:
13,108
WBT
Author by

WBT

Longtime SE contributor. Not a fan of the company's recent shift away from the community. I welcome diversity. People of all ages, genders, races, religions, national origins, sexual orientations, levels of physical ability, background, etc. are welcome here in my view. If one must judge, do so by contributions. If one doesn't like the idea or doesn't think it's well supported, go after the idea or evidence or lack thereof; personal attacks on the messenger are unwarranted and unhelpful. I will not express offense on the basis of anyone using any common respectful pronouns or titles to refer to me on SE, so you can focus your energy on the substance of what you're trying to say.

Updated on June 04, 2022

Comments

  • WBT
    WBT almost 2 years

    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?

  • WBT
    WBT about 6 years
    To summarize the solution in this answer, it's to change the problematic comparison on line 9 to read if(typeof someGlobal === "undefined"). Thank you for your answer!