Hello World Master

Tutorials, articles and quizzes on Software Development

Javascript > Articles

Understanding Array.unshift

Lets say I have an array of numbers and I want to add a new number to the beginning or that array

For example: Lets say we have an array of numbers like this

[1,2,3,4,5]

And we want to add the number zero to the beginning of the array.

We could create a new array that would have the first index be zero

Here is an example of that

const arr = [1,2,3,4,5];
const newarr = [0];
for(let i = 0; i < arr.length; i++) {
   newarr.push(arr[i]);
}

This works but we could do the exact same thing in one function

The unshift() method allows us to add elements to the beginning of our array.

So we can simply call arr.shift() for our array of numbers

const arr = [1,2,3,4,5];
arr.unshift(0);
console.log(arr); // returns [0,1,2,3,4,5]

We can add more arguments to our parameters so we aren’t limited to just adding one value in a single call to unshift

const arr = [1,2,3,4,5];
arr.unshift(0,.5,.7);
console.log(arr);  // returns [0,.5,.7,1,2,3,4,5]