Main difference between [splice] and [slice]:
const arr = [1, 2, 3, 4, 5];
// splice — modifies array
const removed = arr.splice(1, 2); // Removes 2 elements from index 1
console.log(arr); // [1, 4, 5] — array changed!
console.log(removed); // [2, 3] — removed elements
// slice — doesn't modify array
const part = arr.slice(1, 3); // Takes elements from 1 to 3 (excluding 3)
console.log(arr); // [1, 4, 5] — array unchanged
console.log(part); // [4, 5] — new partImagine you have a box with items. [slice] is like taking a photo of part of the box, while [splice] is like taking items out of the box! 📦📸 vs 📦👐
Creates a copy of part of the array without touching original:
const fruits = ['apple', 'banana', 'orange', 'pear'];
// Copy elements from index 1 to 3 (excluding 3)
const copy = fruits.slice(1, 3);
console.log(copy); // ['banana', 'orange']
// Original unchanged!
console.log(fruits); // ['apple', 'banana', 'orange', 'pear']
// Can omit second parameter — to end
const rest = fruits.slice(2); // ['orange', 'pear']Physically removes elements from array and returns them:
const fruits = ['apple', 'banana', 'orange', 'pear'];
// Remove 2 elements from index 1
const removed = fruits.splice(1, 2);
console.log(removed); // ['banana', 'orange'] — removed elements
// Original changed!
console.log(fruits); // ['apple', 'pear']const arr = [1, 2, 3, 4];
const copy = arr.slice(1, 3); // Only copies, doesn't add
// Can't add elements through slice!const arr = [1, 2, 3, 4];
// Remove 1 element from index 1 and add new ones
arr.splice(1, 1, 'new', 'elements');
console.log(arr); // [1, 'new', 'elements', 3, 4]// ✅ When you need part of array
const numbers = [1, 2, 3, 4, 5];
const middle = numbers.slice(1, 4); // [2, 3, 4]
// ✅ For copying entire array
const copy = numbers.slice(); // [1, 2, 3, 4, 5]// ✅ When you need to modify array
const items = [1, 2, 3, 4, 5];
items.splice(2, 2); // Remove 2 elements from index 2
console.log(items); // [1, 2, 5]const arr = [1, 2, 3, 4];
// ❌ Mistake — think slice modifies array
const part = arr.slice(1, 3);
console.log(arr); // [1, 2, 3, 4] — unchanged!
// ❌ Mistake — think splice doesn't modify array
const removed = arr.splice(1, 2);
console.log(arr); // Changed!const arr = [1, 2, 3, 4];
// ❌ Mistake — don't understand what's returned
const result1 = arr.slice(1, 3); // Returns [2, 3]
const result2 = arr.splice(1, 2); // Returns [2, 3]
// ❌ Mistake — think splice returns new array
// Actually it returns REMOVED elements!Understanding the difference between [slice] and [splice] helps work with arrays correctly! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪