Interview question
What is the difference between slice() and splice()? slice() और splice() में क्या अंतर है?
Answer
| Method | Mutates original? | Returns | Purpose |
|---|---|---|---|
| slice(start, end) | No | New array (shallow copy of a portion) | Extract a section without changing original |
| splice(start, count, ...items) | Yes | Array of removed elements | Remove/insert/replace elements in place |
const arr = ['a', 'b', 'c', 'd', 'e'];
// SLICE - non-mutating, extracts a portion
const sliced = arr.slice(1, 3); // start index 1, up to (not including) 3
console.log(sliced); // ['b', 'c']
console.log(arr); // ['a', 'b', 'c', 'd', 'e'] - unchanged
// Negative indices count from the end
console.log(arr.slice(-2)); // ['d', 'e']
// Common use: copying an array
const copy = arr.slice();
console.log(copy === arr); // false - different array, same values
// SPLICE - mutates the original array
const arr2 = ['a', 'b', 'c', 'd', 'e'];
// Removing elements: splice(startIndex, deleteCount)
const removed = arr2.splice(1, 2); // remove 2 elements starting at index 1
console.log(removed); // ['b', 'c'] - the removed elements
console.log(arr2); // ['a', 'd', 'e'] - original is mutated!
// Inserting elements: splice(startIndex, 0, ...newItems)
const arr3 = ['a', 'b', 'e'];
arr3.splice(2, 0, 'c', 'd'); // insert without removing anything
console.log(arr3); // ['a', 'b', 'c', 'd', 'e']
// Replacing elements: splice(startIndex, deleteCount, ...newItems)
const arr4 = ['a', 'b', 'X', 'd'];
arr4.splice(2, 1, 'c'); // remove 1 element at index 2, insert 'c'
console.log(arr4); // ['a', 'b', 'c', 'd']
// Memory tip: sLice does NOT mutate (like 'slice a cake, keep the rest'),
// sPlice DOES mutate (splices/cuts the original wire)| Method | Original बदलता है? | Return | उद्देश्य |
|---|---|---|---|
| slice(start, end) | नहीं | नया array | बिना बदले हिस्सा निकालना |
| splice(start, count, ...items) | हाँ | हटाए गए elements का array | Elements remove/insert/replace करना |
const arr = ['a', 'b', 'c', 'd', 'e'];
// SLICE - mutate नहीं करता
const sliced = arr.slice(1, 3);
console.log(sliced); // ['b', 'c']
console.log(arr); // बदला नहीं
// Negative indices
console.log(arr.slice(-2)); // ['d', 'e']
// Array copy करना
const copy = arr.slice();
// SPLICE - original को mutate करता है
const arr2 = ['a', 'b', 'c', 'd', 'e'];
// Elements हटाना
const removed = arr2.splice(1, 2);
console.log(removed); // ['b', 'c']
console.log(arr2); // ['a', 'd', 'e'] - मूल बदल गया!
// Elements insert करना
const arr3 = ['a', 'b', 'e'];
arr3.splice(2, 0, 'c', 'd');
console.log(arr3); // ['a', 'b', 'c', 'd', 'e']
// Elements replace करना
const arr4 = ['a', 'b', 'X', 'd'];
arr4.splice(2, 1, 'c');
console.log(arr4); // ['a', 'b', 'c', 'd']Was this answer clear?