Confusing JavaScript: slice or splice?

In this article, I shall talk about two pretty useful functions in JavaScript named slice and splice, but the confusion rests amongst the programmers regarding both of these functions that when to use them and why to use them.

Let us discuss them one by one.

slice

First, why not read the official document working of slice? According to the official reference documentation of JavaScript, slice is:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

Takeaways:

  1. It makes a new array and returns that.
  2. The original array is not modified.

Examples of slice

Case 1: With No Arguments

const array= [1,2,3,4];

const arrayCopy= array.slice();

console.log(arrayCopy);

// Output -> [1,2,3,4]

The example with no arguments show that it will return the copy of original array.

Case 2: With One Argument

With one argument, a copy of array will be returned from the specified index to the end of the array:

const array= [1,2,3,4];

const arrayCopy= array.slice(2);

console.log(arrayCopy);

// Output -> [3,4]

Case 3: With A Negative Argument

The argument to the slice function can be negative, in which case the starting index is calculated from the end:

const array= [1,2,3,4];

const arrayCopy= array.slice(-3);
console.log(arrayCopy);

// Output -> [2, 3, 4]

Case 4: With Two Arguments

const array= [1,2,3,4];

const arrayCopy= array.slice(-3, 2);

console.log(arrayCopy);
    
// Output -> [2]

splice

First, why not read the official document working of splice? According to the official reference documentation of JavaScript, splice is:

The method that changes the contents of an array by removing existing elements and/or adding new elements.

Takeaways:

  1. It does not make a new array.
  2. The original array is modified.

Examples of splice

Case 1: With One Argument

All the items after the provided argument-starting index are removed from the array:

let array= [1,2,3,4];

array.splice(2);

console.log(array); 
// Output -> [1,2]

Case 2: With Two Arguments

The second argument is for the number of items to remove:

let array= [1,2,3,4];

array.splice(2,1);

console.log(array); 
// Output -> [1,2,4]

Case 3: Appending More Arguments

An random arguments can be passed at the end and will be added to the array:

let array= [1,2,3,4];

array.splice(2,1, 10, 11);

console.log(array); 
// Output -> [1,2,10,11,4]

Summary

In this article, I have discussed slice and splice functions of JavaScript with many cases and examples. I hope the concept will now be clear! That's it for this article!

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?