πͺ Distinguishing slice() vs splice() in JavaScript
How much of a difference does a βpβ make? π€

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! π



