Skip to content

Array length assignment truncation surprise

Quick summary

You set arr.length = 2 to 'resize' — elements beyond index 1 are silently and permanently removed.

Why this happens

  • Setting array.length to a smaller number to truncate

  • Confusing length assignment with slice (which returns a copy)

  • Using length assignment in a loop that shrinks the array unexpectedly

Minimal example

✗ Broken code
const arr = [1, 2, 3, 4, 5];
arr.length = 2;
console.log(arr); // [1, 2] — 3,4,5 gone forever
✓ Fixed code
const arr = [1, 2, 3, 4, 5];
const truncated = arr.slice(0, 2);
console.log(truncated); // [1, 2]
console.log(arr); // [1, 2, 3, 4, 5] — original intact

Setting .length mutates and permanently deletes trailing elements. slice(0, n) returns a truncated copy and leaves the original unchanged.

How to diagnose

  • Log the array before and after the length assignment

  • Search for assignments to .length

  • Use slice(0, n) if you want a truncated copy without mutation

How to fix

  • Use slice(0, n) to get a truncated copy without mutating the original

  • If truncation is intended, add a comment and make it explicit

  • Use splice(n) to remove elements and capture the removed items

How to prevent

  • Avoid assigning to .length — use slice for copies

  • Treat arrays as immutable and use spread or slice

Related Resources

Related Glossary

Related Lessons

← Back to language