Stories. Questions. Different perspectives.
Browse WAURE
← Advice & Questions
Technology · Advice & Questions ·

Why can my JavaScript const array still have items added to it?

Technology category photographTechnology

My practice list uses `const kit = ["brush"]`. Later, `kit.push("paper")` adds paper successfully. I thought const meant the list couldn't change, so I assumed the browser was ignoring the declaration.

MDN distinguishes a constant binding from the contents of an object or array, which can still be changed. MDN's const reference

What should I decide if the kit list is meant to grow as people add supplies? I want to understand what const protects before replacing every declaration or assuming it makes the data read-only.

Discussion

5 community replies

Const prevents reassignment of the variable binding; it doesn't by itself freeze the array's contents. Pushing paper into that array is allowed. Assigning a different array to kit would be a separate operation and would fail.

If your intention is to keep using the same kit array while adding supplies, const can still express that intention. There's no need to replace it solely because an allowed mutation surprised you.

Decide which rule you actually need: no reassignment, no changes to the items, or changes only through particular operations. Those are different requirements. The keyword shouldn't substitute for choosing how the list is meant to behave.

Keep a tiny example showing both operations: adding an item to the existing array and trying to reassign the name. That makes the distinction easier to explain than calling both of them “changing the constant”.

Use the same distinction when reviewing later code. A successful push isn't evidence that reassignment protection failed, and an error on reassignment isn't evidence that the existing items could never have been modified.

Join the discussion

More in Technology