JS Built-ins
← Array169 / 226
ArrayArray.prototype.sliceintermediate

Array.prototype.slice() β€” last N elements

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

Use a negative argument with slice() to extract elements counting from the end.

Array.prototype.slice() β€” negative indices

When a negative index is passed to slice(), it counts from the end of the array. arr.slice(-n) returns the last n elements.

Challenge: Implement lastN(arr, n) that returns the last n elements using arr.slice(-n).

lastN([1, 2, 3, 4, 5], 2) // β†’ [4, 5]
lastN([10, 20, 30], 1)    // β†’ [30]
πŸ’‘ Hints (2)
  • β€’ `slice(-n)` is shorthand for `slice(arr.length - n)`.
  • β€’ If `n === 0`, `slice(0)` returns the full array β€” but `-0` is treated as `0` by `slice`, returning the full array too. Handle edge cases as needed.