Slice and Splice in JavaScript.

Slice and Splice in JavaScript.

Table of contents

In this article we will learn the difference between slice() and splice() methods in JavaScript.

slice()

The slice() method returns a part of the array. It does not affect the original array. Instead it creates a shallow copy of the array.

Syntax:

slice(start , end)

  • The count(index) starts from 0.

  • The array is sliced from the start index but it excludes the end index.

const players = ["Virat" , "ABd" , "Gayle", "Dhoni", "Bumrah" , "Starc"];

var result = players.slice(0 , 3);
console.log(result);    //[ 'Virat', 'ABd', 'Gayle' ]
const players = ["Virat" , "ABd" , "Gayle", "Dhoni", "Bumrah" , "Starc"];

var result2 = players.slice(2);
console.log(result2);           //[ 'Gayle', 'Dhoni', 'Bumrah', 'Starc' ]

In the above code, the start index is 2.

const players = ["Virat" , "ABd" , "Gayle", "Dhoni", "Bumrah" , "Starc"];

var result2 = players.slice(-3);
console.log(result2);           //[ 'Gayle', 'Dhoni', 'Bumrah', 'Starc' ]

In the above code, we have used negative index, so the slice(-3) method returns the last four names.

splice()

Theb splice() method is used to modify an array in JavaScript. It can be used to add, delete or replace an element from the array.

Syntax:

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

  • start specifies the starting index from where the array is to be modified.

  • deleteCount specifies number of items to remove. It is optional .

  • item1, ......itemN specifies the elements to add to the starting index. It is also optional.

const scores = [133 , 129 , 113 , 90 , 175 , 149 , 183];
scores.splice(1, 1 , "Hey");
console.log(scores);   // [133, 'Hey', 113, 90,  175,   149, 183]
  • The first argument to splice is 1, which means to start removing elements from index 1 (i.e. 129).

  • The second argument to splice is 1, which means to remove one element starting from the index.

  • The third argument to splice is "Hey" , which means to insert the string "Hey" in place of the removed element.

const scores = [133 , 129 , 113 , 90 , 175 , 149 , 183];
scores.splice(1, 2 , "Hey");
console.log(scores);   // [ 133, 'Hey', 90, 175, 149, 183 ]

In the above code, starting from index 1, two elements are deleted and "Hey" is inserted at that position.

const scores = [133 , 129 , 113 , 90 , 175 , 149 , 183];
scores.splice(1, 0 , "Hey");
console.log(scores);   // [133, 'Hey', 129, 113, 90, 175, 149, 183]

In the above code, no elements are deleted, instead, we have inserted "Hey" after the first element.

I hope this blog helped you understand the difference between slice() and splice() in JavaScript. Thank You.

Did you find this article valuable?

Support Venky's Blog by becoming a sponsor. Any amount is appreciated!