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

Written by Raymon Schouwenaar on

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.


Latest posts

What is the JavaScript Set in ES2015 and when should you use it?

The ES2015 spec is full of new features that continuously be introduced in all the new browsers. The Set collection is one of those new things.

My first thought was, well I could just use a normal Array! But I will show you what you can do with the Set collection.

CSS Grid Layout Metro design blocks

The times have come that we don’t have to fiddle around with Floats and Tables anymore! Flexbox is already an established term in the industry of Frontend Developers.