Js Array: Slice vs Splice
The
slice()
method ofArray
instances returns a shallow copy of a portion of an array into a new array object selected fromstart
toend
Shallow copy!
A shallow copy creates a new object or array but only copies references to nested objects instead of duplicating them. Changes to nested objects affect both the original and copied structures.
const obj1 = { name: "Hassan", details: { age: 23 } };
const obj2 = { ...obj1 }; // shallow copy
obj2.details.age = 30;
console.log(obj1.details.age);
Demo
Syntax Sugar
slice()
slice(start)
slice(start, end)
const animals = ["ant", "bison", "camel", "duck", "elephant"];
const anothersliced = animals.slice(1)
const sliced = animals.slice(1,3)
console.log(anothersliced)
console.log(sliced)
// [ 'bison', 'camel', 'duck', 'elephant' ]
// [ 'bison', 'camel' ]
Splice Method
The
splice()
method of Array. instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
Demo
const animals = ["ant", "bison", "camel", "duck", "elephant"];
const anotherspliced = animals.splice(1)
const spliced = animals.splice(1,3)
console.log(anothersliced)
console.log(sliced)
// [ 'bison', 'camel', 'duck', 'elephant' ]
// [ 'bison', 'camel', 'duck' ]
What You think is that the key difference between slice and splice is that slice not returns last end index value and splice does. WRONG !!
Key Difference
Splice method modify original array while Slice does’nt.
const animals = ["ant", "bison", "camel", "duck", "elephant"];
const sliced = animals.slice(1)
console.log(sliced)
console.log(animals)
// [ 'bison', 'camel', 'duck', 'elephant' ]
// [ 'ant', 'bison', 'camel', 'duck', 'elephant' ]
Splice:
const animals = ["ant", "bison", "camel", "duck", "elephant"];
const spliced = animals.splice(1)
console.log(spliced)
console.log(animals)
// [ 'bison', 'camel', 'duck', 'elephant' ]
// [ 'ant' ]
See ! Animals array restrict to ant !
HAPPY JAVASCRIPT !