Low level difference between Slice and Splice methods in Javascript


The basic difference between slice and splice is −

  • splice() changes the original array on which it is called and returns the removed item(s) in an array as a new array object.

  • slice() doesn't change the original array and also returns the array sliced.

Example

// splice changes the array
let arr = [1, 2, 3, 4, 5];
console.log(array.splice(2));
//slice doesn't change original one
let arr2 = [1, 2, 3, 4, 5];
console.log(array2.slice(2));
console.log("\n After Changing the arrays");
console.log(array);
console.log(array2);

Output

[ 3, 4, 5 ]
[ 3, 4, 5 ]

After Changing the arrays

[[ 1, 2 ]
[ 1, 2, 3, 4, 5 ]
raja
Published on 16-Sep-2019 10:26:26
Advertisements