JavaScript Splice vs Slice: Exploring Differences and Use Cases

Are you looking for JavaScript splice vs slice? Also, wondering what’s the difference between splice and slice()?

In this guide, you will be able to know what is splice and slice at the same time. Besides that, we will explore example programs that demonstrate how these methods work.

What is Splice?

The splice() function in JavaScript enables you to alter an array by removing, replacing, or adding elements at a particular position.

This function directly modifies the original array, making it mutable.

It accepts various parameters, such as the starting index, the optional number of elements to be removed, and the optional elements to be added.

Syntax

The syntax for this method is as follows:

array.splice(start, deleteCount, item1, item2, ...)

start: The index from which to begin making changes to the array. If a negative number is provided, it counts from the end of the array.
deleteCount: The number of elements to be taken out from the array. If set to 0, no elements are removed.
item1, item2, …: Optional. Elements to be added to the array at the specified position.

Return Value

The return value of the splice() method in JavaScript is an array containing the elements that were removed from the original array. If no elements are removed (i.e., the deleteCount is set to 0), an empty array is returned.

How does splice in JavaScript work?

Here is the example code that demonstrates how splice() works.

let fruits = ['apple 🍎', 'banana 🍌', 'orange 🍊', 'mango πŸ₯­'];

// Remove 'banana 🍌' from the array
fruits.splice(1, 1);

console.log(fruits);  // Output: ['apple 🍎', 'orange 🍊', 'mango πŸ₯­']

// Add 'pear' and 'grape' at index 2, without removing any elements
fruits.splice(2, 0, 'pear 🍐', 'grape πŸ‡');

console.log(fruits);  

Output:

(3) ["apple 🍎", "orange 🍊", "mango πŸ₯­"...]
(5) ["apple 🍎", "orange 🍊", "pear 🍐",...]

What is slice?

The slice() method in JavaScript allows you to extract a portion of an array into a new array, without modifying the original array.

It takes in two parameters: the starting index (optional) and the ending index (optional).

Syntax

The syntax for slice() is as follows which is for array and string:

For array:

array.slice(start, end)

For strings:

string.slice(start, end)

  • start: The index at which to begin extraction. If a negative number is provided, it counts from the end of the array or string.
  • end: Optional. The index at which to end extraction (excluding the element at this index). If not provided, the extraction extends until the end of the array or string. If a negative number is provided, it counts from the end of the array or string.

Return Value

The return value of the slice() method in JavaScript is a new array or string that contains the extracted elements or characters. The original array or string is not modified by the slice() method.

How does splice in JavaScript work?

Here’s an example that demonstrates the usage of slice():

For arrays:

let fruits = ['apple 🍎', 'banana 🍌', 'orange 🍊', 'mango πŸ₯­'];

let slicedFruits = fruits.slice(1, 3);

console.log(slicedFruits);  // Output: ['banana 🍌', 'orange 🍊']

Output:

["banana 🍌", "orange 🍊"]

For strings:

let sentence = ' The slice() method in JavaScript allows you to extract a portion of an array into a new array.';

let slicedSentence = sentence.slice(4, 9);

console.log(slicedSentence); 

Output:

 slic

Example Use Cases of splice vs slice javascript

Here are common Use Cases for splice vs slice().

Use Cases of splice

  • Removing elements from array:
const numbers = [10, 20, 30, 40, 50];
const removed = numbers.splice(2, 2);
console.log(numbers); 
console.log(removed); 

Output:

[10, 20, 50]
[30, 40]
  • Adding elements into array:
const fruits = ['apple 🍎', 'banana 🍌', 'cherry πŸ’'];
fruits.splice(2, 0, 'orange 🍊', 'grape πŸ‡');
console.log(fruits); 

Output:

["apple 🍎", "banana 🍌", "cherry πŸ’...]
  • Replacing elements into an array:
const animals = ['cat', 'dog', 'elephant'];
animals.splice(1, 1, 'lion');
console.log(animals); // ['cat', 'lion', 'elephant']

Output:

["cat", "lion", "elephant"]

Use Cases for slice():

  1. Extracting a portion of an array:
const numbers = [1, 2, 3, 4, 5];
const subArray = numbers.slice(1, 4);
console.log(subArray); // [2, 3, 4]
  1. Creating a shallow copy of an array:
const original = [1, 2, 3, 4, 5];
const copy = original.slice();
console.log(copy); // [1, 2, 3, 4, 5]
  1. Converting an array-like object to an array:
const arrayLike = document.querySelectorAll('.item');
const convertedArray = Array.prototype.slice.call(arrayLike);
console.log(convertedArray); // Array of selected elements

To learn more about JavaScript functions here are other resources you can check out:

Conclusion

In conclusion, understanding the differences between splice vs slice in JavaScript is crucial for effective array manipulation.

Remember, splice modifies the original array and allows for adding, removing, and replacing elements, while slice creates a new array without modifying the original.

By leveraging the power of these methods, you can confidently work with arrays in JavaScript and write cleaner, more efficient code.

Leave a Comment