Splice || Slice ? which is which...

Splice || Slice ? which is which...

·

2 min read

Today I will try and break down the differences between splice and slice methods to all javascript fans out there. let's dive straight in shall we...☺

.splice()

The splice method mutates the original array by adding, removing or replacing elements at a given index.

The time complexity of this method varies depending on how many elements are to be added or removed in relation to the length of the array. The longer the array the greater the shift. This means its worst time complexity is O(N) with N being the length of the array.

syntax is :

array.splice(index, deleteCount, item1, ..., itemX)

examples:

let array = [1,2,3,4,5,6]
const newArray = array.splice(3,2);
console.log(newArray); //Output [4,5]
console.log(array); //Output [1,2,3,6]
const cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
cities.splice(3, 1, 'Nairobi');
console.log(cities); 
//Output ["Chicago", "Delhi", "Islamabad", "Nairobi", "Berlin"];

.slice()

This method does not mutate the original array but it does return a copy/portion of the original array in a new array.

Its time complexity is also linear : O(N) with N being the length of the array. It has to create a copy of the array elements and return a new array.

syntax is:

array.slice(start, end)

Kindly remember, the index where it ends is non-inclusive meaning it's not included in the returned array.

examples:

function foreCast(arr){
    return arr.slice(2,4)
}
console.log(
    foreCast(['cold','sunny','rainy','warm','storm','thunders'])
);
//Output: ['rainy', 'warm'] 
//non inclusive of storm even though 4 ends at storm

Feel free to engage more and leave your comments below.

thanks!!