how to use slice() or splice() in JavaScript
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.
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
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
- Array.prototype.slice(). developer.mozilla.org
- Array.prototype.splice(). developer.mozilla.org
- JavaScript Array slice() Method. w3schools.com
- JavaScript Array splice() Method. w3schools.com
- JavaScript Tip: Using slice and splice. Youtube.com