Lessons · TypeScript · reassigning a const
const fixes the name, not the contents
const means the variable cannot be pointed at something else; the object or array it points to can still change.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
People either avoid const because 'it cannot change' or are surprised when a const array grows. Both come from the same misreading.
How to think about it
Use const by default. Ask: will I reassign this name? Only then use let. Mutating an array with push is not reassignment.
Worked example
const list = [1];The name list points at an array.
list.push(2);Fine: same array, changed contents.
// list = [3];TypeError: assignment to constant. The NAME is fixed.
Your turn
Declare a total that will be reassigned in a loop.
total = 0; for (const n of nums) total += n;
Solve one with the tests running
The trap
Reaching for let everywhere 'to be safe'. It hides intent; const tells the reader this name never moves.
Practise reassigning a const on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.