Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

What are undeclared and undefined variables in JavaScript?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Undefined: It occurs when a variable has been declared but has not been assigned 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 the var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with the return value as “undefined”. The scope of the undeclared variables is always global. 

For example:

Undefined: 

let geek;
undefined
console.log(geek) 

Undeclared: 

//ReferenceError: myVariable is not defined
console.log(myVariable) 

Example 1: This example illustrates a situation where an undeclared variable is used. 

javascript




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

Output: 

ReferenceError: x is not defined

Example 2: This example checks whether a given variable is undefined or not. 

html




<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
 
<body>
    <h1 style="color:green;">GeeksforGeeks.</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>

Output: 

 


My Personal Notes arrow_drop_up
Last Updated : 24 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials