Thursday, May 7, 2026
HomeLanguagesJavascriptJavaScript ReferenceError – variable is not defined

JavaScript ReferenceError – variable is not defined

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
RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6891 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12105 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6962 POSTS0 COMMENTS