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

Array.prototype.slice() β€” shallow copy

πŸ“– Usage Example
const original = [1, 2, 3]
const copy = original.slice()  // shallow copy
copy !== original  // β†’ true

Call slice() with no arguments to create a shallow copy of an array.

Array.prototype.slice() β€” copying an array

Calling slice() with no arguments returns a shallow copy of the entire array. This is a common pattern to duplicate an array without mutating the original.

Challenge: Implement shallowCopy(arr) that returns a full copy using arr.slice().

shallowCopy([1, 2, 3]) // β†’ [1, 2, 3]  (new array reference)
πŸ’‘ Hints (2)
  • β€’ `arr.slice()` with no arguments is equivalent to `arr.slice(0)`.
  • β€’ The returned array is a new object β€” modifying it does not affect the original.