Monday, January 6, 2025
Google search engine
HomeLanguagesJavascriptWhat are undeclared and undefined variables in JavaScript?

What are undeclared and undefined variables in JavaScript?

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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments