Skip to main content

Command Palette

Search for a command to run...

πŸ”ͺ Distinguishing slice() vs splice() in JavaScript

How much of a difference does a β€˜p’ make? πŸ€”

Published
β€’2 min read
πŸ”ͺ Distinguishing slice() vs splice() in JavaScript

Hey folks! Today let’s look into another common JavaScript question: Distinguish between slice() and splice() in JavaScript πŸš€

πŸ”· Slicing Arrays with slice():

slice() is a handy method for extracting a portion of an array. It always creates a new array and does not modify the original array, making it perfect for non-destructive operations. This method takes two arguments: the starting index (inclusive) and the ending index (exclusive). It will return a new array which will contain the elements from the starting index till the element before the ending index.

const fruits = ['apple', 'banana', 'cherry', 'date', 'fig'];
const slicedFruits = fruits.slice(1, 4);
console.log(slicedFruits); // Output: ['banana', 'cherry', 'date']

πŸ”Ά Splicing Arrays with splice():

splice() is a powerful method for adding or removing elements from an array. Unlike slice(), splice() modifies the original array so it is destructive. It takes three arguments: the starting index, the number of elements to remove, and optional elements to add. It returns an array of the removed elements.

const colors = ['red', 'green', 'blue', 'yellow', 'orange'];
const removedColors = colors.splice(1, 2, 'purple', 'pink');
console.log(colors); // Output: ['red', 'purple', 'pink', 'yellow', 'orange']
console.log(removedColors); // Output: ['green', 'blue']

🌟 When to use?

  • Use slice() when you want to create a new array that's a subset of an existing array without modifying the original.

  • Use splice() when you need to remove or add elements within an array, altering the original array.

Feel free to share your favorite array manipulations or any tips you have for using slice() and splice() effectively in the comments below. Happy coding and array crafting! πŸš€