JS Capsules: Array.splice() vs Array.slice()

JS Capsules: Array.splice() vs Array.slice()

Introduction

While working with arrays, most developers often find it challenging to differentiate between Array.prototype.splice() and Array.prototype.slice().

In this article, we will look at these two array methods, understand how they work, and know when to use each one.


Array.splice()

Syntax

Array.splice(startIndex, deleteCount, newElement);

Key things to note

  • This method modifies an existing array.

  • It takes in three parameters: startIndex, deleteCount(optional), and newElement(optional).

  • startIndex indicates which index of the array to start from.

  • deleteCount indicates how many elements to remove from the array.

  • newElement contains any element(s) to add to the array from the startIndex.

Examples

Our initial array

// ==== Array.prototype.splice() ====
// INITIAL ARRAY
const gadgets = ['phone', 'laptop', 'headphones', 'earbuds'];

Example 1

// ==== Example 1 ====
/*
Starting from index 3,
-> remove 0 elements
-> add 'solar lamp', 'clock', 'watch'
*/
gadgets.splice(3, 0, 'solar lamp', 'clock', 'watch');

// -> print to console
console.log(gadgets);

/*
[
  'phone',
  'laptop',
  'headphones',
  'solar lamp',
  'clock',
  'watch',
  'earbuds'
]
*/

Here we did the following:

  • Inserted 'solar lamp', 'clock', and 'watch' in the gadgets array, starting from index 3.

  • The second parameter - 0 - means no existing element of the array gets replaced.

  • We printed our updated gadgets to the console.

Example 2

// ==== Example 2 ====
/*
Starting from index 5 in our updated gadgets[] array,
-> remove 1 element
-> add 'smart watch'
*/
gadgets.splice(5, 1, 'smart watch');

// -> print to console
console.log(gadgets);

/*
[
  'phone',
  'laptop',
  'headphones',
  'solar lamp',
  'clock',
  'smart watch',
  'earbuds'
]
*/

In the code above, we did the following:

  • Removed one element from our updated gadgets array, starting from index 5.

  • Added 'smart watch' to the array at index 5.

  • Printed our updated gadgets array to the console.

Example 3

// ==== Example 3 ====
/*
Starting from index 3 in our updated gadgets[] array,
-> remove 2 elements
*/
gadgets.splice(3, 2);

// -> print to console
console.log(gadgets);

/*
[ 'phone', 'laptop', 'headphones', 'smart watch', 'earbuds' ]
*/

Here, we did the following:

  • Removed two elements from our updated gadgets array from index 3.

  • Printed the gadgets array to the console in its current state.

Example 4

We can also get the values we removed with splice() by storing them in a variable:

// based on Example 3
const deletedGadgets = gadgets.splice(3, 2);
console.log(deletedGadgets)
/*
[ 'solar lamp', 'clock']
*/

Array.slice()

Syntax

Array.slice(startIndex, endIndex);

Key things to note

  • This method copies a specific range of elements into a new array.

  • The original array remains the same (it doesn't get modified).

  • It takes in two parameters: startIndex(optional) and endIndex(optional).

  • startIndex indicates where to begin copying elements.

  • endIndex indicates where to stop. The slice() method will not copy the element in this index.

Examples

Our initial array

// ====Array.prototype.slice() ====
// INITIAL ARRAY
const grocery = [
  'tomatoes',
  'pumpkin leaves',
  'eggs',
  'meat',
  'fish',
  'onions',
];

Example 1

// ==== Example 1 ====
/*
-> copy all elements from index 2 to index 5 
    except the element at index 5
*/
let protein = grocery.slice(2, 5);

// -> print to console
console.log(protein);

/*
[ 'eggs', 'meat', 'fish' ]
*/

Here, we did the following:

  • Copied all elements from grocery[2] to grocery[5], except grocery[5].

  • Stored our copied elements as an array in a protein variable.

Example 2

If we specify only the startIndex, it will copy all the elements from that startIndex till the end of the array:

// ==== Example 2 ====
/*
-> copy all elements from index 1 to the end of the array
*/
const noTomatoes = grocery.slice(1);

// -> print to console
console.log(noTomatoes);

/*
[ 'pumpkin leaves', 'eggs', 'meat', 'fish', 'onions' ]
*/

Example 3

If our startIndex is negative, it will count backward from the end of the array and copy the last n elements:

// ==== Example 3 ====
/*
-> copy three elements backward from the end of the array
*/
const lastThree = grocery.slice(-3);

// -> print to console
console.log(lastThree);

/*
[ 'meat', 'fish', 'onions' ]
*/

Conclusion

These two array methods - splice() and slice() - might be tricky to understand at first, but with careful practice, we can learn to differentiate between them and apply the right one for our specific use case. An excellent tip to remember is: splice() modifies the existing array while slice() copies it without any modifications.