Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

What are undeclared and undefined variables in JavaScript?

  • Difficulty Level : Medium
  • 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;
  • Undeclared:
    //ReferenceError: myVariable is not defined
  • Example 1: This example illustrate a situation where an undeclared variable is used.

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


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

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!