Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Low level difference between Slice and Splice methods in Javascript
The slice() and splice() methods are often confused due to their similar names, but they behave very differently. Understanding their key differences is crucial for array manipulation in JavaScript.
Key Differences
splice()modifies the original array by adding, removing, or replacing elements and returns an array of removed items.slice()creates a shallow copy of a portion of the array without modifying the original and returns the extracted elements.
Syntax Comparison
// splice syntax array.splice(startIndex, deleteCount, item1, item2, ...) // slice syntax array.slice(startIndex, endIndex)
Example: Demonstrating the Difference
// splice changes the original array
let arr1 = [1, 2, 3, 4, 5];
let spliceResult = arr1.splice(2, 2); // Remove 2 elements starting from index 2
console.log("Splice result:", spliceResult);
console.log("Original array after splice:", arr1);
// slice doesn't change the original array
let arr2 = [1, 2, 3, 4, 5];
let sliceResult = arr2.slice(2, 4); // Extract elements from index 2 to 4 (exclusive)
console.log("Slice result:", sliceResult);
console.log("Original array after slice:", arr2);
Splice result: [ 3, 4 ] Original array after splice: [ 1, 2, 5 ] Slice result: [ 3, 4 ] Original array after slice: [ 1, 2, 3, 4, 5 ]
Detailed Comparison
| Feature | splice() | slice() |
|---|---|---|
| Mutates Original | Yes | No |
| Return Value | Array of removed elements | New array with extracted elements |
| Can Add Elements | Yes | No |
| End Index | Delete count (not index) | End index (exclusive) |
Practical Use Cases
// Use splice to remove and add elements
let fruits = ['apple', 'banana', 'orange', 'grape'];
fruits.splice(1, 2, 'mango', 'kiwi'); // Remove 2, add 2
console.log("Modified fruits:", fruits);
// Use slice to create a copy of part of array
let numbers = [10, 20, 30, 40, 50];
let subset = numbers.slice(1, 4); // Get elements from index 1 to 3
console.log("Subset:", subset);
console.log("Original numbers:", numbers);
Modified fruits: [ 'apple', 'mango', 'kiwi', 'grape' ] Subset: [ 20, 30, 40 ] Original numbers: [ 10, 20, 30, 40, 50 ]
Conclusion
Use splice() when you need to modify the original array by adding or removing elements. Use slice() when you want to extract a portion of an array without changing the original.
Advertisements
