Open In App
Related Articles

JavaScript ReferenceError – variable is not defined

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

This JavaScript exception variable is not defined and occurs if there is a non-existent variable that is referenced somewhere.

Message:

ReferenceError: "x" is not defined

Error Type:

ReferenceError

Cause of Error:

There is a non-existent variable that is referenced somewhere in the script. That variable has to be declared or make sure the variable is available in the current script or scope.

Example 1: In this example, the variable(val1) is being accessed from the outside of the function, So the error has not occurred.

Javascript

function sum() {
    let val1 = 2;
    let val2 = 3;
    return val1 + val2;
}
console.log(val1);

                    

Output:

ReferenceError: 'val1' is not defined

Example 2: In this example, the variable(GFG) is not defined, So the error has occurred.

Javascript

GFG.substring(2);

                    

Output:

ReferenceError: 'GFG' is not defined

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks 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!


Last Updated : 22 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials