What is the difference between Array.slice() and Array.splice() in JavaScript ?

In JavaScript, slice() and splice() are array methods with distinct purposes. `slice()` creates a new array containing selected elements from the original, while `splice()` modifies the original array by adding, removing, or replacing elements.

slice():

The slice() method in JavaScript extracts a section of an array and returns a new array containing the selected elements, without modifying the original array.

Syntax:

array_name.slice(s, e)

Example: In this example The slice() method in JavaScript extracts elements from the cars array, creating a new array new_cars from index 1 up to, but not including, index 4.

JavaScript
let cars = ['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire'];
let new_cars = cars.slice(1, 4);
console.log("cars :", cars);
console.log("new_cars :", new_cars);

Output
cars : [ 'Benz', 'Innova', 'Breeza', 'Etios', 'Dzire' ]
new_cars : [ 'Innova', 'Breeza', 'Etios' ]

splice():

The splice() method in JavaScript is used to change the contents of an array by removing or replacing existing elements and/or adding new elements in place, modifying the original array.

Syntax:

array_name.splice(i, n, item 1, item 2, .....item n)

Example: In this example, The splice() method in JavaScript inserts new elements (‘ambassador’, ‘BMW’, ‘Audi’) into the cars array at index 2 without removing any elements.

javascript
let cars = ['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire'];
cars.splice(2, 0, 'ambassedor', 'BMW', 'Audi');
console.log("cars :", cars);

Output
cars : [
  'Benz',       'Innova',
  'ambassedor', 'BMW',
  'Audi',       'Breeza',
  'Etios',      'Dzire'
]

Difference Table between Array.slice() and Array.splice()

slice()splice()
This method is used to get a new array by selecting a sub-array of a given array. This method is used to add/remove an item from the given array.
The parameter ‘s’ indicates the starting index and ‘e’ indicates the ending index. They denote the index of the sub-array to be taken. By default, the value for start is ‘0’ and end is ‘n’.The parameter ‘i’ denotes the starting index, ‘n’ denotes the number of items to be removed from the specified starting index.‘item 1, item 2, …..item n’ represents the list of new items to be added at the given index. If n=0, no item is removed, the new items are just added to the specified starting index.
The changes do not reflect in the original array.The changes are reflected in the original array
The result has to be assigned to a new array variable.The result need not be assigned to any other new variable.
The return value is a new array with the values in the selected sub-array of the given array. The values in the range start to (end-1) will be selected.The return value is an array containing the deleted element.
Takes exactly 2 argumentsTakes ‘n’ number of arguments (a list of new items can be supplied)