splice vs. slice in JavaScript

slice and splice are methods used on JavaScript arrays to retrieve certain elements or remove elements from the array. They can be confusing sometimes, but we’ll be looking at the methods in detail to get a better picture.

slice

The term slice literally means to cut something into pieces. It is used to cut out elements from an array. It does not affect the original array.

Syntax

array.slice(start, end)
  • start denotes the index at which the array starts slicing.
  • end denotes the index at which the array stops slicing.

Return value

The returned value of the slice method is an array of the values found between start and end excluding the value at end.

If end is not specified, the length of the array would be used. Hence, all values from the start index would be returned.

Example

let arr = [
"educative",
4,
[1,3],
{type: "animal"}
];
let slicedValues = arr.slice(1,3);
console.log(arr);
console.log(slicedValues);

As stated in the syntax above, 1 is the starting index and 3 is the ending index.

At arr[1], the value is 4. At arr[3], the value is {type: "animal"}. The values between these two values are [1,3]. Therefore, the returned value would be the subarray [4, [1,3]]. Remember, the value at the last index is excluded.

But arr retains its values.

splice

Splice, according to the dictionary, means to join things together. It is used to remove elements from an array or replace them.

Syntax

array.splice(start, deleteCount, newElem1, newElem2, ..., newElemN;
  • start denotes the index from which the method will start its operation on the array.
  • deleteCount denotes the number of values to be deleted from the start. If the value is 0, nothing will be deleted.
  • newElem1 to newElemN denote the values that would be added after the start.

Return value

The returned value is the values that are affected,i.e., deleted. If deleteCount is 0, an empty array would be returned.

Example

let arr = [
"educative",
4,
[1,3],
{type: "animal"}
];
let returnedArr = arr.splice(2,1,{name: "educative"});
console.log(arr);
console.log(returnedArr);

arr, the original array, is modified and becomes:

[
    "educative",
    4,
    {name: "educative"},
    {type: "animal"}
]

start is 2, deleteCount is 1, newElem1 is {name: "educative"}. At arr[2], the value is [1,3]. 1 item is deleted from the array which is [1,3]. newElem1 is then added immediately after the start. Since start is removed, newElem replaces it.

returnedArr is [[1,3]], which contains the value that was affected.

Wrap up

slice returns a piece of the array but it doesn’t affect the original array. splice changes the original array by removing, replacing, or adding values and returns the affected values.

When you use each one is up to you. If you have to alter the content of the array, splice is the way to go, but if you just want to obtain a subarray, slice should be your choice.

Free Resources