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

Array.prototype.length β€” extend with sparse holes

πŸ“– Usage Example
const arr = [1, 2, 3]
arr.length = 5
arr  // β†’ [1, 2, 3, <2 empty items>]

Assigning a larger number to length creates a sparse array with empty slots at the end.

Array.prototype.length β€” extending

Setting arr.length to a value larger than the current length extends the array. The new slots are empty (holes) β€” they exist as indices but have no assigned value.

Challenge: Implement extend(arr, n) that sets arr.length = n and returns the new length.

extend([1, 2], 5) // β†’ 5  (arr is now [1, 2, <3 empty items>])
extend([], 3)     // β†’ 3
πŸ’‘ Hints (3)
  • β€’ Setting `arr.length` to a larger value creates sparse "holes".
  • β€’ The new slots are `undefined` when accessed but are technically empty.
  • β€’ Return `arr.length` after the assignment to get the updated value.