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

istanbul medyummedyumizmir medyumankara medyum
HacklinkHair Transplant istanbul
hacklink
istanbul evden eve nakliyat
hair transplant
istanbul anl?k haberler
extrabet
cratosroyalbet
casibom
romabet
romabet
romabet
casibom
casibom
marsbahis
holiganbet
casibom
https://deneme-bonuslarim-yeni.com/
deneme bonusu veren siteler
https://deneme-bonuslari-listesi.com/
deneme bonusu veren siteler
deneme bonusu veren siteler
deneme bonusu veren siteler
deneme bonusu veren siteler
Betpas
adana escort
esenyurt masaj salonubeylikdüzü masaj salonumasaj salonuesenyurt masaj salonubeylikdüzü masaj salonuba?ak?ehir masaj salonuavc?lar masaj salonumasaj salonuesenyurt masaj salonubeylikdüzü masaj salonuavc?lar masaj salonubahçe?ehir masaj salonu?irinevler masaj salonuesenyurt masaj salonumasaj salonuesenyurt masaj salonubeylikdüzü masaj salonuesenyurt masaj salonuesenyurt masaj salonuesenyurt escortesenyurt escortesenyurt escortesenyurt masaj salonuavc?lar masaj salonubeylikdüzü masaj salonumaltepe escortescort ?spartaescort fethiye