JavaScript splice method is used to add a new element in an array without deleting any element in it. Lets learn how splice method works behind the scene.
Theory :
Consider a Array declared as
let arr=[1,2,3,4,5]
Suppose we want to add new element at index 2, that means we have change the position of element at index 2 by replacing it somewhere else and add a new value there.
We will do so by replacing the position of last element to it's n+1 position (if there are n elements consider) which means we will replace the number 5 to a new position at index 5 (remember indexing starts from 0). Similarly we will shift the second last element to the position of last element and this process will continue until the element at position that we have to place the new number is replaced. This will create a empty space at index 2 where we will will insert our element.
let data =[60,30,10,67,40];
let newEl= 70;
let position=2;
for(let i=data.length-1;i>=0;i--){
if(i>=position){
data[i+1]=data[i];
if(i==position){
data[i]=newEl;
}
}
}
Practical explanation :
As seen from the code we have declared some variables, array, new element and position where we want to enter new element.
Next a for loop is created which will starts from the last element.
First the loop will changed the position of element as discussed above.
If the the position where we want to insert element will reach, the loop does adds a new element to that position.
Thats how the splice() method in JavaScript works behind the scenes. The code syntax may be different but logical and approach is same.
Top comments (0)