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

Always curious about using slice() and splice() in the most efficient manner. https://media.giphy.com/media/FowpjcLMH2KNa/giphy.mp4
  • 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.
  • 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

Resources

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Toni T Diep

Toni T Diep

multilingual Software Engineer, always learning and growing.