JavaScript TypeError – Invalid assignment to const “X”

This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared.

Message:

TypeError: invalid assignment to const "x" (Firefox)
TypeError: Assignment to constant variable. (Chrome)
TypeError: Assignment to const (Edge)
TypeError: Redeclaration of const 'x' (IE)

Error Type:

TypeError

Cause of Error: A const value in JavaScript is changed by the program which can not be altered during normal execution. 

Example 1: In this example, the value of the variable(‘GFG’) is changed, So the error has occurred.



HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    const GFG = "This is GFG";
    // Error here
    GFG = "This is GeeksForGeeks"; 
</script>

chevron_right


Output(in console):

TypeError: Assignment to const

Example 2: In this example, the value of the object(‘GFG_Obj’) is changed, So the error has occurred.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    const GFG_Obj = {key: 'val1'};
    // Error here
    GFG_Obj = {key: 'val2'}; 
</script>

chevron_right


Output:

TypeError: Assignment to const

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


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