Array.splice() vs Array.slice()

In this post, we are going to know the difference between JavaScript : Array.splice() vs Array.slice().


Slice is an array method to manipulate the arrays. In arrays slice() method returns the selected elements in an array, as a new array object. It extracts the characters of an array and returns the extracted characters as an new array. It has two parameters ‘Start’ and ‘End’.

The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn’t change the original array.

array.slice(from, until);

  • From: Slice the array starting from an element index
  • Until: Slice the array until another element index

For example, I want to slice the first three elements from the array above. Since the first element of an array is always indexed at 0, I start slicing “from”0.

array.slice(0, until);

Now here is the tricky part. When I want to slice the first three elements, I must give the until parameter as 3. The slice( ) method doesn’t include the last given element.

var array=[1,2,3,4,5]
// shows [3, 4, 5], returned selected element(s).
// shows [4, 5], returned selected element(s).
// shows [1, 2, 3, 4, 5], original array remains intact.


Splice is an array method, which is used to add/remove the new elements to an array.

The name of this function is very similar to slice( ). This naming similarity often confuses developers. The splice( ) method changes an array, by adding or removing elements from it. Let’s see how to add and remove elements with splice( ):

Removing Elements

For removing elements, we need to give the index parameter, and the number of elements to be removed:

array.splice(index, number of elements);

Index is the starting point for removing elements. Elements which have a smaller index number from the given index won’t be removed:

array.splice(2);  // Every element starting from index 2, will be removed

If we don’t define the second parameter, every element starting from the given index will be removed from the array.

var array=[1,2,3,4,5];
// shows [3, 4, 5], returned removed item(s) as a new array object.
// shows [1, 2], original array altered.
var array2=[6,7,8,9,0];
// shows [8]
//shows [] , as no item(s) removed.
// shows [6,7,9,0]
var array3=[11,12,13,14,15];
// shows [13]
// shows [11, 12, "Hello", "World", 14, 15]
           -5 -4 -3 -2 -1
            |  |  |  |  |
var array4=[16,17,18,19,20];
             |  |  |  |  |
             0  1  2  3  4
// shows  [19]
// shows [16, 17, 18, "me", 20]

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button