Slice vs Splice Method in Javascript

Quick Note: If you don’t understand anything or have any questions or just want to talk about tech, you can connect with me on Instagram, Facebook or twitter

4. Slice Method vs Splice method

  1. the splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object
  2. The splice() method changes the original array and slice() method doesn’t change the original array.
  3. The splice() method can take n number of arguments

Splice Method

Argument 1: Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.

Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.

Argument 3…n : Optional. The new item(s) to be added to the array.

let array = [1,2,3,4,5];
//This will log all the elements removed hence {3, 4, 5}
//It will remove the element from the orginal array and hence if we
// shows [1, 2], original array altered.
//In more human terms
var array = [1,2,3,4,5];
var array2 = array.splice(2)
console.log(array)) //[1, 2] -> return the removed item
console.log(array2) //[3, 4, 5] -> changed the orignal
var array2=[6,7,8,9,0];
// shows [8]
//shows [] , as no item(s) removed.
// shows [6,7,9,0]
var array3=[11,12,13,14,15];
// shows [13]
// shows [11, 12, "Hello", "World", 14, 15]

Slice Method

The slice() method returns the selected elements in an array, as a new array object. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.

Note: The original array will not be changed.

var fruits = ["Banana", "Chips" , "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 5);
//Console log will show Chips,Orange,Lemon,Apple
var array=[0,1,2,3,4,5]
// shows [2,3, 4, 5], returned selected element(s).
// shows [4, 5], returned selected element(s).
// shows [1, 2, 3, 4, 5], original array remains intact.
var array2=[6,7,8,9,0];
// shows [8, 9]
// shows [9]
// shows [8, 9]
// shows [6, 7, 8, 9, 0]
//We can create copy of an object using slice as like this
var fruits = ["Banana", "Chips" , "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(0);
//["Banana", "Chips", "Orange", "Lemon", "Apple", "Mango"]

If in case you are interested to connect with me or have any questions, here are my social profile Instagram, Facebook or twitter

Also don’t forgot to give a clap if you found this article useful