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

Array.prototype.slice() β€” remove first and last

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

Use slice() to exclude the first or last element without mutating the array.

Array.prototype.slice() β€” interior elements

arr.slice(1, -1) removes the first and last element, returning only the interior items. This is useful for stripping delimiters or boundary values.

Challenge: Implement withoutFirstAndLast(arr) that returns arr.slice(1, -1).

withoutFirstAndLast([1, 2, 3, 4, 5]) // β†’ [2, 3, 4]
withoutFirstAndLast([10, 20, 30])     // β†’ [20]
πŸ’‘ Hints (2)
  • β€’ `slice(1, -1)` combines a positive start index with a negative end index.
  • β€’ For arrays with fewer than 2 elements, this returns an empty array.