Array slice v/s splice once and for all!
📅 28 Jun 2020 | ☕️ 3 min read
Hey There! 👋🏽
Do you wish to break this loop and become a JS array ninja who just knows which one of the two is to be used in which case? Then follow along.
Returns a section of the original string without changing the original string
let str = [1, 2, 3, 4, 5, 6, 7]; console.log(str.slice(4)); // [5, 6, 7] console.log(str); // [1,2,3,4,5,6,7];
Changes the contents of the array by removing/replacing existing items
let str = [1, 2, 3, 4, 5, 6, 7]; console.log(str.splice(4)); // [5, 6, 7] console.log(str); // [1,2,3,4];
Here is a mnemonic technique that you can use so that there is no need for another Google search in your entire life while working on JS arrays.
Slice v/s Splice
Notice that splice has an extra p in the method name. Because of that, it pulls the items out of the original array and hence modifies it, and thus, slice does not pull items out of the original array. Also, because it pulls items, it can also push items into the array.
So let's sort this out:
It takes a start index and an end index (excluded) and slices those array items and gives back to you.
let str = [1, 2, 3, 4, 5, 6, 7]; console.log(str.slice(2, 4)); // [3, 4] console.log(str); // [1,2,3,4,5,6,7]; // not modified
splice(startIndex, number, items)
It takes a start index too, but, also pulls the items out of the original array (the number of items can be specified in the number argument) and all the other arguments after than will be pushed into the array!
let str = [1, 2, 3, 4, 5, 6, 7]; console.log(str.splice(2, 4, 8, 9)); // [3, 4, 5, 6] console.log(str); // [1, 2, 8, 9, 7];
Here's a graphic to cement that understanding
Original : Array slice v/s splice once and for all!