Skip to content
Related Articles

Related Articles

What are undeclared and undefined variables in JavaScript?
  • Last Updated : 26 Nov, 2019

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(); //accessing 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:

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :