Javascript Splice vs Slice

2020/2/31 min read
bookmark this
Responsive image

This blog compares how to use Splice versus using Slice at JavaScript.

Array.prototype.slice

slice will create a new array, and won't modify the origin array. As you can see, the following example is trying to get the first 2 items to start from index 0. slice function will return as the result and origin result didn't change. 

let x = [1,2,3,4,5];
let z = x.slice(0,2);

console.log(x);
// [1,2,3,4,5]
console.log(z);
// [1,2]

Array.prototype.splice

On the other hand, the splice will return the same result but also will update the origin result. 

let x = [1,2,3,4,5];
let z = x.splice(0,2);

console.log(x);
// [3,4,5]
console.log(z);
// [1,2]