JS Built-ins
← Array170 / 226
ArrayArray.prototype.slicebeginner

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

πŸ“– Usage Example
const arr = [10, 20, 30, 40, 50]
arr.slice(0, 3)  // β†’ [10, 20, 30]

Use slice(0, n) to get the first n elements of an array as a new array.

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

arr.slice(0, n) returns the first n elements of the array. It is a clean, non-mutating alternative to manually trimming an array.

Challenge: Implement firstN(arr, n) that returns the first n elements using arr.slice(0, n).

firstN([1, 2, 3, 4, 5], 3) // β†’ [1, 2, 3]
firstN([10, 20], 1)         // β†’ [10]
πŸ’‘ Hints (2)
  • β€’ `slice(0, n)` starts at index 0 and stops before index `n`.
  • β€’ If `n` exceeds the array length, you get the full array β€” no out-of-bounds error.