Both the slice() and splice() return a subset or a portion of the array.
What is Slice()
The slice() function accepts two arguments startIndex and endIndex. For instance we have an array
var num = [1,2,3,4,5,6,7] and we need the first three element of the array. So that how you would do it
var num = [1,2,3,4,5,6,7]; var slicedArray = num.slice(0,2); > slicedArray // [1,2,3] // Let's print the original array > num // [1,2,3,4,5,6,7]
Now we have the slicedArray which is a subset of the num array. If you provide any more arguments other than the startIndex and endIntex, slice() function will just ignore them.
Slice() is an immutable function. It means that It will not affect the original array. Looking at the Line No 6 of the above snippet the num array is not affected at all.
But what function will mutate the orignal array?
That is Array.splice()
The splice function works differently than slice. It accepts startIndex and length. The length means the number of array elements to pluck. Let’s make it simpler using a code snippet
var marks = [5,10,15,20,25,30]; var sliced = marks.splice(1,3); > sliced // [10,15,20] > marks // [5,25,30]
Looking at line 3, we get the items that are removed from the marks array. Line 5 confirms that the splice() modifies the original array.
I use splice() most of the time, especially to romove elements from the dom. For me it’s easier to remember it’s syntax. You just need to provide the index. For example countries.slice(1,1) will remove an element at the second index of countries array.
The slice() can also be used to clone an array. Because array are passed by reference. I think I can give an example to expalin this.
var old_array = [1,2,3,4,5]; > old_array // [1,2,3,4,5]; var new_array = old_array; new_array.push(6); > old_array // [1,2,3,4,5,6];
Although we have pushed new element to the new_array but yet the element is also added to the old_array. On the fourth line we are just passing a reference to the old_array not the whole new array. In order to cope with this; we have to go through another code snippet
var new_array = old_array.slice(); new_array.push(6); > old_array // [1,2,3,4,5]
As you can see the new_array is now a whole new array. It’s no more a reference to the old_array.
That’s it for this time around. See you around for more awesome stuff.