Logo


Splice in javascript


The splice method modifies the original array by removing or replacing a new item in the array.the splice method has the following pattren of paramerters: splice(start, deleteCount, item1, item2, itemN).


The first one is the index at which we insert a value, The second one is for insert or replace. If it is greater than '0' then it will replace the current value with the existing values or if it is '0' then it will push the current value and move the other value to the right in the array. The other parameters are the values to be inserted into the array


Below is examples that will clarify the concept.


1) We push value at a specific index in the array.

1const numberz = ['one', 'three', 'four', 'five'];
2  numberz.splice(1, 0, 'two');
3  // inserts at index 1, between one and three
4  console.log(numberz); // expected output: Array ["one", "two", "three", "four", "five"]

In the above example, we push 'two' in-between 'one' and 'three'.


1) We replace value at a specific index in the array.

1const numberz = ['one', 'three', 'four', 'five'];
2  numberz.splice(1, 1, 'two');
3  // inserts at index 1, between one and three
4  console.log(numberz); // expected output: Array ["one", "two", "four", "five"]

In the above example, we replaced 'two' with 'three'.




Related Articles :



About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share