JavaScript Basics: Add something to the beginning of an array in JavaScript

How to add something (Object, Array, String, Number) to an Array in JavaScript. Well that is simply done with the Array.push() method.

var arrayName = ['1', '2', '3'];
arrayName.push({
     property1: 'First property of Object',
     property2: ['Array', 'of', 'Items']
});
arrayName.push('Last item');

The result will be:

[
  '1',
  '2',
  '3',
  {
    property1: 'First property of Object',
    property2: ['Array', 'of', 'Items']
  },
  'Last item'
]

That was simple! Right? Every time you push something to the Array, it will be added to the end. But what if you need to add something to the beginning of the array?

That is also simple, use the Array.unshift() method.

var arrayName = ['1', '2', '3'];
arrayName.unshift({
  property1: 'First property of Object',
  property2: ['Array', 'of', 'Items']
},'Second item');

The result of the code above will be:

[
  {
    property1: 'First property of Object',
    property2: ['Array', 'of', 'Items']
  },
  'Second item',
  '1',
  '2',
  '3'
]

I thought it would be useful in some cases to put something at the beginning of an exciting Array. So I hope this will help you to use it. 🙂

Check the resources of W3Schools if you want to read more about the Array.unshift() or Array.push() method.


Also published on Medium.