how to use slice() or splice() in JavaScript

Toni T Diep
2 min readDec 16, 2021

--

Learning when to manipulate arrays with JavaScript slice() and splice(). There is HELLA of a difference between these two methods.

Always curious about using slice() and splice() in the most efficient manner. https://media.giphy.com/media/FowpjcLMH2KNa/giphy.mp4

slice() the copy of the original array does not change.

  • syntax: array.slice(value1, value2)
  • 1st argument signifies the starting element
  • 2nd argument signifies the ending argument
  • 2nd argument is optional
  • will not mutate the array
arr = [1, 2, 3, 4, 5]
arr1 = arr.slice(1, 2)
//return by console.log (below)//console.log(arr1) => [2]
//points to index 1 on element number 2 from the first argument as we do not include the index 2’s element from the 2nd argument comes at a hard stop.
console.log(arr)=> [1, 2, 3, 4, 5]
//return and copy of the original array--no mutation of this.

splice() the copy of the original array changes.

  • syntax: array.splice(start, delete)
  • remove and add array objects overwriting the original array with a new array copy from the original arrays, so mutations of the arrays are happening here.
  • will mutate the array
www.w3schools.com%2Fjsref%2Fjsref_splice.asp

Wisdom Tea: rejection is redirection best of luck on self-learning and anything this mantra can bring perspectives in your process(s) (i.e. job hunts).

If you like the read, clap it — thank you.

Happy Coding, Friends.

Resources

--

--

Toni T Diep
Toni T Diep

Written by Toni T Diep

multilingual Software Engineer, always learning and growing.