JS Built-ins
← Array129 / 226
ArrayArray.prototype.lengthintermediate

Array.prototype.length β€” truncate by setting length

πŸ“– Usage Example
const arr = [1, 2, 3, 4, 5]
arr.length = 3
arr  // β†’ [1, 2, 3]  (elements truncated)

Assign a smaller value to length to truncate an array in place.

Array.prototype.length β€” truncation

You can shorten an array by assigning a smaller value to its length property. Elements beyond the new length are removed and the array is mutated in place.

Challenge: Implement truncate(arr, n) that sets arr.length = n and returns the (now shorter) array.

truncate([1, 2, 3, 4, 5], 3) // β†’ [1, 2, 3]
truncate([1, 2, 3], 0)       // β†’ []
πŸ’‘ Hints (2)
  • β€’ Assigning to `arr.length` mutates the array in place.
  • β€’ Setting `arr.length = 0` is a common way to empty an array while keeping the same reference.