iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Array Const

Declaring an array with const doesn't make it immutable — it only protects the binding. The contents can still change.

What const actually locks

JS
const items = [1, 2, 3];

// ✓ Mutating the contents is allowed
items.push(4);
items[0] = 99;
items.length = 0;            // empties the array

// ❌ Reassigning the binding is not
items = [];                  // TypeError: Assignment to constant variable

Truly immutable arrays

JS
const frozen = Object.freeze([1, 2, 3]);
frozen.push(4);              // TypeError in strict mode (silent in sloppy)
frozen[0] = 99;              // ignored / TypeError

// Use the non-mutating array methods for clean updates
const next = frozen.toSorted();        // returns a NEW array
const withFour = [...frozen, 4];       // spread copy

Why pick const for arrays

ReasonBenefit
Self-documentingReaders see "this variable will not be reassigned".
Catches typosAccidental items = … throws instead of silently rebinding.
Plays with lintersESLint's prefer-const rule expects it.
Compatible with mutationsYou can still push, pop, splice.
Tip: Default to const for every array and object. If you find yourself wanting to reassign, switch to let — but most of the time you're really wanting a new value, which destructuring or spread can express.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Array Const!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Truly freeze an array so its contents cannot change.

const items = Object. ([1, 2, 3]);

Test yourself

Q1. `const arr = [1, 2]; arr.push(3);` is…
Q2. Truly immutable arrays use…
Q3. Non-mutating sort is…

Discussion

Loading…