DEV Community

Cover image for slice( ) and splice( ) array methods in JavaScript
hebaShakeel
hebaShakeel

Posted on

slice( ) and splice( ) array methods in JavaScript

The array slice( ) method

This method returns a shallow copy or a new array object of a portion of an array. It does not modify (immutable) the original array on which it is called upon. It selects the elements starting at the given start argument, and ends at the given optional end argument without including the last element.
By default, the starting index will be 0 and the last index will be array.length but we can specify what index we want.

Example:

Alt Text

We observe from the above example that the 'numbers' array is not modified which means we still have the original array.

Now, consider an example where we do not provide any index.
Alt Text

This simply generates a shallow copy of the original array

What output would we obtain if we passed a negative index. Let's take a look.

Example:

Alt Text

This prints the last three elements of the array.

Notice that in this array method, the value provided at the last index is not included.

Remember: Slice method does not mutate the original array but it returns the subset as a new array, so you can use this method inside a function which receives an array as a parameter, while being sure that you still have the original array.

The array splice( ) method

This array method modifies an array by removing or replacing existing elements in it. It takes the starting index, the count(number of elements you want to remove) and it also optionally takes new elements which are placed at the end of the array.
This method changes the array on which it is called upon and returns an array with the removed or replaced items.

Example:

Alt Text

From the above example, we observe that our original array has been manipulated.

Now, consider an example where you want to add additional elements at the end of your array using the splice method.

Alt Text

What if you don't want to delete any element from your array, rather you want to add few elements at a specified position in your original array? Let's take a look at how this can be done:

Alt Text

Remember: The splice method mutates your original array on which it is called upon.

Until next time...
Take Care!

Top comments (0)