What are undeclared and undefined variables in JavaScript?

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 geek;
    undefined
    console.log(geek) 
    
  • Undeclared:
    //ReferenceError: myVariable is not defined
    console.log(myVariable) 
    
  • Example 1: This example illustrate a situation where an undeclared variable is used.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
    function GFG(){
    //'use strict' verifies that no undeclared 
    // variable is present in our code
       'use strict'
       x = "GeeksForGeeks";
    }
      
     GFG(); //accesing the above function
    </script>

    chevron_right

    
    

    Output:

    ReferenceError: x is not defined
  • Example 2: This example checks whether a given variable is undefined or not.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html>
    <html>
      
    <body>
        <style>
            h1 {
                color: green;
            }
        </style>
      
        <h1>UNDEFINED OR NOT.</h1>
      
        <button onclick="checkVar()">
          Try it
      </button>
      
        <p id="gfg"></p>
      
        <script>
            function checkVar() {
                if (typeof variable === "undefined") {   
                    string = "Variable is undefined";
                } else {   
                    string = "Variable is defined";
                }
                document.getElementById("gfg").innerHTML = 
                  string;
            }
        </script>
      
    </body>
      
    </html>

    chevron_right

    
    

    Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.