When working with JavaScript arrays, developers often get confused between the slice and splice methods. They might sound similar, but their functionalities are distinct.

The Gentle `slice`

The slice() method returns the selected elements in an array as a new array object or extract a section of an array without altering the original.

Basics of slice:

  • Purpose: Extracts a part of the array and returns it as a new array.
  • Original Array: Remains untouched.
let colors = ["red", "blue", "green", "yellow"];
let selectedColors = colors.slice(1, 3);
console.log(selectedColors);  // ["blue", "green"]
console.log(colors);          // ["red", "blue", "green", "yellow"]

Here, colors remains unchanged. We only took a ‘slice’ of it.

The Versatile `splice`

The splice() method is used either adds/removes items to/from an array, and then returns the removed item. splice is about surgically altering it. With splice, you can remove, replace, or add pieces (elements) to the pie (array).

Basics of splice:

  • Purpose: Alters the content of an array by removing, replacing, or adding elements.
  • Original Array: Gets modified.
 let animals = ["cat", "dog", "fish", "bird"];
let removedAnimals = animals.splice(1, 2, "hamster", "lizard");
console.log(removedAnimals);  // ["dog", "fish"]
console.log(animals);         // ["cat", "hamster", "lizard", "bird"]

In the example above, “dog” and “fish” were removed from animals, replaced by “hamster” and “lizard”.

SliceSplice
Doesn’t modify the original array(immutable)Modifies the original array(mutable)
Returns the subset of original arrayReturns the deleted elements as array
Used to pick the elements from arrayUsed to insert or delete elements to/from array

0 Comments

Leave a Comment