How to add an element in the begging of an array in JavaScript

Arun kumar
1 min readApr 25, 2021

In array addition of a new element at the last position of an array is not a big deal either you can assign a value at a position of its length or you can use a push method, let see an example

let arr = [1, 2, 3, 4];

you want to add 5 in last of this array then you can write here

arr[arr.length] = 5;

now array is [1, 2, 3, 4, 5];

but if you want to add 5 in the begging of array then you can use Unshift method but i don’t want to use unshift method, so here i am going to add a element using for loop.

for(let i= arr.length; i >=0; i — ){

arr[i] = arr[i-1];

}

now array is [undefined, 1, 2, 3, 4 ], so now we will assign the element at the position of index 0

arr[0] = 5;

now array is [5, 1, 2, 3, 4];

actually here we are shifting element in right one by one, initially at the position of arr[arr.length] we are assigning a value which is at position arr[arr.length-1] and so on and at last at the position of arr[0] we are assigning a value which we want to add.

--

--