Open In App

What are undeclared and undefined variables in JavaScript?

Last Updated : 20 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Javascript




function checkVar() {
    let string;
 
    if (typeof variable === "undefined") {
        string = "Variable is undefined";
    } else {
        string = "Variable is defined";
    }
     
    console.log(string);
}
 
checkVar();


Output

Variable is undefined

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads