The “splice” method does not only replacing an element or elements, but also removing or adding an element or elements in the middle of an Array. In fact, removing and adding elements at a certain position in array are “replacing”. It is safe to say that the method, “splice”, adds and removes an element or elements at specific position of an array, which also means “replacing the elements in the array”.
The method, “splice”, takes 3 or more parameters of which one is required and the others are optional.
The first parameter indicates the starting index. It means where to start replacing. The second parameter indicates how many elements from the starting index will be replaced. The parameters after the 2nd indicates what will be replaced with.
Rather than documentation-like verbal explaination, I would like go through with simple examples.
Mission1: replace single element “Mar” at index 1 with “Feb”!
It changes the original array, months, to [“Jan”, “Feb”, “Mar”, “April”] as expected.
Mission2: replace multiple elements
The method, “splice”, is capable of replacing more than one element by setting the second and third paramters.
It changes the original array to [“Jan”, “Feb”, “Feb2”, “April”] as expected.
If you change the second paramter to 3, you get to replace 3 elements from the starting index.
Mission3: replace multiple elements with the spread operator!
Being a bit more creative, I tried to replace elements using the spread operator of other array.
It changes the original array to [“Jan”, “Feb”, “Feb2”, “Feb4”] as expected.
What does the method returns?
We have checked “splice” changes the original array. Then what does it return? Let me test it with the simple code below.
It turns out that it returns an array with removed elements from the original array.
This is it.
Thank you for reading my post. I hope this post helped you.