Js Array: Slice vs Splice

Muhammad Hassan Saeed
2 min readMar 11, 2025

--

Photo by Claudio Schwarz on Unsplash

The slice() method of Array instances returns a shallow copy of a portion of an array into a new array object selected from start to end

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 !

--

--

Muhammad Hassan Saeed
Muhammad Hassan Saeed

Written by Muhammad Hassan Saeed

Full Stack Developer | Aws-Certified SAA

No responses yet