Home » Javascript » How to use array.push() to add item to a JavaScript array

How to use array.push() to add item to a JavaScript array

By Emily

If you’ve been working with JavaScript arrays then at some point you will need to know how to use JavaScript array.push(). It’s the command you use to add an item to the end of an array, and can also be used to push multiple elements to an array.

Additionally the JS array.push() method also returns the new length of the array after the item(s) have been added.

This post looks at different ways of using the method and provides code examples that you can use in your own applications.

Add an item to an array using .push()

This example shows how to add 1 item to the end of a JS array using the array.push() method. The item “four” will be added to the bottom of the array. Using push not only adds an item to the array, it also gets you the array length as a return value :

//define array
const numbers = ['one', 'two', 'three'];
// expected output: Array ['one', 'two', 'three']

//add string using push
const count = numbers.push('four');
// expected output: 4

// expected output: Array ['one', 'two', 'three', 'four']

Add an array to a JS array

You can also add several items to a JavaScript array in one line using the .push() command, which is the same as saying ‘push an array into a JavaScript array’), or ‘add an array to the end of an array‘.

const numbers = ['one', 'two', 'three', 'four'];
const count = numbers.push('five', 'six');
// expected output: 6 - which is the NEW length of the array

// expected output: Array ['one', 'two', 'three', 'four', 'five', 'six']

In this example you can see how the value returned from the push method is the new length of the array after the collection of items have been added.

Push an object into a JavaScript array

Above I’ve shown how to add a string to a JS array using .push(). What about if you want to add an object to a JavaScript array? In this example I’ll create an object, and then use push() to add it to the end of the array.

//define object
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

//define array
const team = ['Jack', 'Susan'];

//push the object into the array

In the image below you can see the console.log output of:

  • the object
  • the array (team)
  • the array after using the array.push(object) command
How to push object into javascript array