Skip to content

JavaScript array insert at 0 | Example code

  • by

Use Array unshift method to insert an element at 0 indexes into the JavaScript array. The unshift. It’s like push, except it adds elements to the beginning of the array instead of the end.

array.unshift(item1, item2, ..., itemX)
  • unshift/push – add an element to the beginning/end of an array
  • shift/pop – remove and return the first/last element of an array

A simple diagram

   unshift -> array <- push
   shift   <- array -> pop

Source: stackoverflow.com

JavaScript array insert at 0

Simple example code adds new elements to the beginning of an array.

<!DOCTYPE html>
<html>
<body>

<script>

   const fruits = ["B", "O", "A", "M"];
   fruits.unshift("X","Y");

   console.log(fruits)

 </script>

</body>
</html> 

Output:

JavaScript array insert at 0

More example

var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a);

With ES6, use the spread operator ...:

var arr = [23, 45, 12, 67];
arr = [34, ...arr]; // RESULT : [34,23, 45, 12, 67]

console.log(arr)

Another way to do that is through concat:

var arr = [1, 2, 3, 4, 5, 6, 7];
console.log([0].concat(arr));

The difference between concat and unshift is that concat returns a new array. The performance between them could be found here.

Do comment if you have any doubts or suggestions on this JS array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *