Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 4 of 10 · Array Methods
Interview question

What is the difference between slice() and splice()? slice() और splice() में क्या अंतर है?

Answer
MethodMutates original?ReturnsPurpose
slice(start, end)NoNew array (shallow copy of a portion)Extract a section without changing original
splice(start, count, ...items)YesArray of removed elementsRemove/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)
MethodOriginal बदलता है?Returnउद्देश्य
slice(start, end)नहींनया arrayबिना बदले हिस्सा निकालना
splice(start, count, ...items)हाँहटाए गए elements का arrayElements 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?