JavaScript ReferenceError – variable is not defined

This JavaScript exception variable is not defined 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.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script
    function sum() { 
        var val1 = 2; 
        var val2 = 3;
      return val1 + val2;
    }
    document.write(val1);
</script>

chevron_right


Output:

ReferenceError: 'val1' is not defined

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

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script
    GFG.substring(2);                
</script>

chevron_right


Output:

ReferenceError: 'GFG' is not defined

full-stack-img

My Personal Notes arrow_drop_up

Recommended Posts:

    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.