Skip to content

TypeError: Assignment to constant variable

Error message

                Assignment to constant variable.
              

Quick summary

You declared a variable with const and then tried to assign a new value to it — const variables cannot be reassigned.

Why this happens

  • Declared a variable with const but later tried to reassign it

  • Copied code that reassigns a variable that was changed to const

  • Assumed const works like let for reassignment

Minimal example

✗ Broken code
const count = 0;
count = 1;
✓ Fixed code
let count = 0;
count = 1;

const prevents reassignment. Change to let if the variable needs to change.

How to diagnose

  • Find the const declaration for the variable

  • Look for any reassignment of that variable later in the code

  • Decide if the variable should be let (if reassignment is needed) or const (if not)

How to fix

  • Change const to let if the variable needs to be reassigned

  • Remove the reassignment if the variable should stay constant

  • Create a new variable for the new value instead of reassigning

How to prevent

  • Use const by default; change to let only when reassignment is needed

  • Understand that const prevents reassignment but not mutation of objects

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language