Slice vs Splice in JavaScript: Key Differences Explained
Muhammad Jareer

Muhammad Jareer @muhammadjareer

About: A passionate frontend developer!

Location:
Pakistan
Joined:
Nov 15, 2024

Slice vs Splice in JavaScript: Key Differences Explained

Publish Date: Mar 26
0 0

When working with arrays in JavaScript, two commonly used methods are slice() and splice(). While they might seem similar at first glance, they serve very different purposes. In this article, we’ll break down their differences, usage, and when to use each one.


🔹 What is slice()?

The slice() method is used to extract a portion of an array without modifying the original array. It returns a new array containing the selected elements.

Syntax


array.slice(start, end)

Enter fullscreen mode Exit fullscreen mode
  • start: The index where extraction begins.
  • end (optional): The index where extraction stops (not included in the result).

Example


let fruits = ["apple", "banana", "cherry", "date"];
let citrus = fruits.slice(1, 3);

console.log(citrus); // ["banana", "cherry"]
console.log(fruits); // ["apple", "banana", "cherry", "date"] (unchanged)

Enter fullscreen mode Exit fullscreen mode

📌 Key Takeaways:

  • Returns a new array.
  • Does not modify the original array.
  • The end index is not included.

🔹 What is splice()?

The splice() method is used to modify the original array by adding or removing elements at a specified position.

Syntax


array.splice(start, deleteCount, item1, item2, ...)

Enter fullscreen mode Exit fullscreen mode
  • start: The index where the modification begins.
  • deleteCount: The number of elements to remove.
  • item1, item2, ...: Elements to be added (optional).

Example: Removing Elements


let colors = ["red", "blue", "green", "yellow"];
colors.splice(1, 2);

console.log(colors); // ["red", "yellow"]

Enter fullscreen mode Exit fullscreen mode

Here, it removes 2 elements starting from index 1 ("blue" and "green").

Example: Adding Elements


let numbers = [1, 2, 3, 5];
numbers.splice(3, 0, 4);

console.log(numbers); // [1, 2, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

Here, we insert 4 at index 3 without removing anything.

📌 Key Takeaways:

  • Modifies the original array.
  • Can remove elements.
  • Can add elements.

Conclusion

  • slice() returns a new array without modifying the original.
  • splice() modifies the original array by adding/removing elements.
  • Choose slice() when you need a portion of an array without altering it.
  • Use splice() when you need to change the array in place.

Understanding these differences will help you write cleaner, more efficient JavaScript code!

Happy Coding! 🤩

If you have any questions or suggestions, feel free to connect with me on LinkedIn or email me at m.ahmar2496@gmail.com. You can also check out my Portfolio.

Comments 0 total

    Add comment