This title could have been β€œhow not to get confused between JavaScript’s splice and slice,” because I can never remember the difference between the two.

So I am hoping this trick will help both me and you in the future:

S (p) lice = Slice + (p) => Slice + in (p) lace

Array.prototype.slice()

Array.prototype.slice() is used to slice an array from the start point to the end point, excluding the end.

As the name suggests, it is used to slice elements out of an array. But unlike slicing a cake, slicing an array does not cut the actual array, but keeps it unmodified (infinite cake!).

arr.slice(start, [end])

Rules

  1. A new array is returned and the original array is unmodified.
  2. If end is omitted, end becomes the end (last element) of the array.
  3. If start is -ve, the elements are counted from the end.
const infiniteCake = ['🍰','🍰','🍰','🍰','🍰','🍰']

let myPieceOfCake = infiniteCake.slice(0) // ['🍰']
let yourDoublePieceOfCake = infiniteCake.slice(0,2) // (2) ["🍰", "🍰"]
console.log(infiniteCake) //['🍰','🍰','🍰','🍰','🍰','🍰']

#javascript #developer

JavaScript Array Slice vs Splice: the Difference Explained with Cake
13.55 GEEK