Slice vs Splice in Javascript

Slice vs Splice 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 look at the methods in detail to get a better picture.

Slice

The term slice means to cut down into pieces. In the same way, slice is used to cut down the element from the array. In simple words, it cut down the specific part and leaves the rest. 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 return value of the slice method is the value found between start and end excluding the value at the 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

const name = ["Rishabh", "Pragya", "Deepak", "Upendra"];
let slicedValue = name.slice(1,3);
console.log(name);
console.log(slicedValue);

Screenshot 2022-08-25 at 3.56.08 PM.png

As stated in the syntax above, 1 is the starting index and 3 is the ending index. At name[1] the value is "Pragya" and at name[3] value is "Upendra", the value between these two is sliced off and assigned toslicedValue, but you can see that the name array remains unaffected.

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, newElement1, newElement2, ..., newElementN);

  • 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.
  • newElement1 to newElemementN denote the values that would be added after the start.

Example

const name = ["Rishabh", "Pragya", "Deepak", "Upendra"];
let splicedValue = name.splice(1,2,"John");
console.log(name);
console.log(splicedValue);

Screenshot 2022-08-25 at 11.41.40 PM.png

As you can see that the original array is modified, and the splice method returns the affected values start is 1 and deleteCount is 2 so starting from index 1 we count till 2 i.e index 1 and intex 2 and newElement is "John" so it is added immediately after start.

splicedValue is "Pragya", "Deepak", which contains the value that was affected.

Conclusion

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.

Thanks for reading 😊