DEV Community

Cover image for Javascript Array Methods Ep.2
Adesh Khanna
Adesh Khanna

Posted on

Javascript Array Methods Ep.2

Hey There 👋
Welcome to Episode 2 of my Array Methods Explain Show.

as always, if you are here then i suppose you must have pre knowledge of javascript and arrays.

we will be discussing only one method in this episode
which is : SPLICE

This is the best method in javascript arrays armoury, as it can be used to insert, replace or delete an element from an array.

the syntax of splice method is :
Syntax

  • start :
The starting index from which you want to modify the array. 
If start > length of array, then start will be set to length of array. 
If start = -1, then start will be set to last element
Enter fullscreen mode Exit fullscreen mode
  • deleteCount (optional) :
The count of elements you want to remove starting from start, if its value is equal or larger than array.length then all elements are removed. 
If its value is 0, then no element is removed, but then providing item1 parameter becomes compulsory.
Enter fullscreen mode Exit fullscreen mode
  • item1, item2, item3, .... itemN :
The elements to add, beginning from start. 
If not provided then only elements are deleted.
Enter fullscreen mode Exit fullscreen mode

It returns an element of deleted array elements, if no element is deleted then empty array is returned.

Now, Let's have a look at some of the examples to have better understanding

  • To remove n elements from ith index. let’s take start as 1 and n as 1
let colors = ["Red", "Blue", "Yellow", "White", "Black"];

colors.splice(1,1); // from index : 1, delete 1 item
console.log(colors); // ["Red", "Yellow", "White", "Black"]
Enter fullscreen mode Exit fullscreen mode
  • Now, lets delete 2 elements and replace them “pink” and “purple”
let colors = ["Red", "Blue", "Yellow", "White", "Black"];

colors.splice(2, 2, "Pink", "Purple"); // from index : 2, delete 2 item, add two items
console.log(colors); // ["Red", "Blue", "Pink", "Purple", "Black"]
Enter fullscreen mode Exit fullscreen mode
  • Now, lets just add one element “grey” without deleting any element
let colors = ["Red", "Blue", "Yellow", "White", "Black"];

colors.splice(1, 0, "Grey"); // from index 1, delete 0 item, add 1 item
console.log(colors); // ["Red", "Grey", "Blue", "Yellow", "White", "Black"]
Enter fullscreen mode Exit fullscreen mode
  • Last, splice returns the array of deleted elements
let colors = ["Red", "Blue", "Yellow", "White", "Black"];

let value = colors.splice(3, 1); // from index 3, delete 1 item
console.log(value); // ["White"]
console.log(colors); // ["Red", "Blue", "Yellow", "Black"]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)