When working with arrays in JavaScript, two commonly used methods for manipulating arrays are slice() and splice(). While at first glance, they may seem similar because they sound alike and both work with arrays, these methods actually behave quite differently.

In this guide, we are exploring the key differences between the slice() and splice() methods. We will look at their syntax, parameters, return values, and examples of usage to understand when and why you would use one versus the other. This guide will provide a detailed splice vs slice comparison to help illuminate the distinct purposes of these array methods.

Slice()

The slice() function creates a duplicate of a specified section of an array in a new array object.  The original array is not modified.

Some key things to know about slice():

Syntax and Parameters

array.slice(begin, end)

  • begin - Optional. The 0-based index at which to begin extraction of elements from the array. If negative, it is treated as the offset from the end of the array. If omitted, slice() defaults to index 0, meaning it copies from the start.
  • end - Optional. The 0-based index at which to end extraction of elements. If negative, it is treated as offset from the end. Slice extracts up to but NOT including the end index. If omitted, extracts through the end of the array.

Return Value

Generates a new array with the extracted items. The original array remains unaltered.

Javascript Slice Examples

Extract a portion from index 1 to 3:

Let fruits = ['Apple', 'Orange', 'Mango', 'Banana'];let citrus = fruits.slice(1, 3); // Returns ['Orange', 'Mango']

Extract from index 1 to end of array:

let fruits = ['Apple', 'Orange', 'Mango', 'Banana'];let allCitrus = fruits.slice(1);// Returns ['Orange', 'Mango', 'Banana']

Handle negative indexes:

let fruits = ['Apple', 'Orange', 'Mango', 'Banana'];let lastTwo = fruits.slice(-2); // Returns ['Mango', 'Banana']

Why Use Slice()?

Use Slice() to extract a part of an array into a new array without modifying it. Some common use cases:

  • Create a sub-array or copy of a portion of an existing array
  • Duplicate entire array to operate on without changing original
  • Split array into multiple smaller chunk arrays for processing
  • Extract copy of array passed into functions without altering it

The slice() method creates shallow copies, not deep copies. It copies object references into a new array instead of entire objects.

Splice()

The splice() function modifies an array by deleting, replacing, or inserting entries at a specified index.

Syntax and Parameters

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

  • start - Required. Index indicating the starting point for modifying the array.
  • deleteCount - Optional. The number of elements to remove from the array from the start index. If 0, no elements are removed.
  • item1, item2, ... - Optional. Add elements to the array starting from the specified start index. If no elements are specified, splice() just removes elements.

Return Value

Returns an array containing the deleted elements. If only elements are added, it returns an empty array.

Javascript Splice Examples

Remove 1 element at index 1:

Explain

let fruits = ['Apple', 'Mango', 'Banana'];let removed = fruits.splice(1, 1);// Returns ['Mango'] // fruits is ['Apple', 'Banana']

Insert elements without removing:

Explain

let fruits = ['Apple', 'Mango', 'Banana'];fruits.splice(1, 0, 'Orange');// Returns []// fruits is ['Apple', 'Orange', 'Mango', 'Banana']

Remove and insert elements:

Explain

let fruits = ['Apple', 'Mango', 'Banana'];fruits.splice(1, 1, 'Lemon', 'Orange'); // Returns ['Mango']// fruits is ['Apple','Lemon','Orange','Banana']

Why Use Splice()?

Splice() allows you to modify the contents of an array by deleting or inserting elements without having to create a new array.

Some common use cases of splice():

  • Insert elements at any index
  • Remove elements by index or value
  • Replace elements by combining remove and insert
  • Clear out array elements
  • Rearrange array elements by moves

Key Differences Between Slice and Splice in JavaScript

While javascript slice vs splice appear similar, they behave differently:

  • Modification - slice() extracts elements into a new array without modifying the original. splice() changes the contents of the original array.
  • Parameters - slice() takes two optional params, begin & end indexes. Splice () requires a start index and optional deleteCount.
  • Return value - slice() returns sliced elements in a new array. splice() returns deleted elements in an array.
  • Use cases - slice() for non-destructive reads from arrays. splice() for destructive changes by inserting/deleting.
Get access and complete hands-on experience on a plethora of software development skills in our unique Job Guarantee bootcamp. Get job-ready with HackerEarth and HIRIST by enrolling in our comprehensive Full Stack Java Developer Masters program today!

Conclusion

Slice() creates a new array by copying elements from an existing array without altering the old array. This is beneficial for replicating or removing a section of array items. Splice() directly mutates the original array by inserting, deleting or replacing elements at a specified index. This is useful for modifications like rearranging array elements. Knowing when to reach for slice() vs splice() based on your specific needs takes practice, but you now have a solid foundation on the splice vs slice comparison!

If you are looking to enhance your software development skills further, we would recommend you to check Simplilearn’s Full Stack Java Developer Course. This course can help you gain the right skills and make you job-ready in no time.

If you have any questions or queries, feel free to post them in the comments section below. Our team will get back to you at the earliest.

FAQs

1. What is the main difference between slice and splice in JavaScript?

The main difference is that slice() creates a new array with a portion of elements copied from the original array, while splice() mutates the original array itself by removing, replacing or adding elements to it.

2. Does the slice modify the original array?

No, slice() does not modify the original array. It returns a shallow copy of selected elements from the original array into a new array without changing the original.

3. Can splice be used to add new elements to an array?

Yes, splice() can be used to add new elements by specifying the new elements as additional arguments after the deleteCount parameter. For example:

let fruits = ['apple', 'mango'];

fruits.splice(1, 0, 'orange'); // insert orange at index 1 

// fruits is now ['apple', 'orange', 'mango']

4. How do you use slice to extract elements from an array?

To extract elements from an array using slice(), you specify the begin and optional end indexes. For example:

let fruits = ['apple', 'orange', 'mango'];

let citrus = fruits.slice(1, 2); // extract 1 element starting at index 1 

// citrus contains ['orange']

5. What happens if you don't provide an end index to slice()?

If you don't provide an end index to slice(), it will extract elements from the provided beginning index to the end of the array. For example:

let fruits = ['apple', 'orange', 'mango'];

let citrus = fruits.slice(1);

// citrus contains ['orange', 'mango']

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449