JavaScript: Add an element to the end of an array.

This is a short tutorial on how to add an element to the end of a JavaScript array. In the example below, we will create a JavaScript array and then append new elements onto the end of it by using the Array.prototype.push() method.

Take a look at the code below:

//An example JavaScript array.
var cars = new Array(
    'Ford', 'Audi', 'BMW'
);

//Log our array to the browser console.
console.log(cars); //(3) ["Ford", "Audi", "BMW"]

//Add an element to the end of our array
cars.push('Honda');

//Add another element.
cars.push('Toyota');

//console.log the array again.
console.log(cars); //(5) ["Ford", "Audi", "BMW", "Honda", "Toyota"]

In the JavaScript above, we:

  1. Created a JavaScript array containing popular car brand names.
  2. Added “Honda” and “Toyota” onto the end of our array by using the push() method.
  3. Finally, we logged our array to the browser’s console.

If you run the example above, you will see that the elements “Honda” and “Toyota” have been successfully added onto the end of our array.

Note that the push() method will return the new length of the array:

//Add another element.
var length = cars.push('Mercedes');
console.log('The array now contains ' + length + ' elements.');

i.e. If you add an element onto an array that originally had 3 elements, then the push() method will return 4.

You can also use the push() method to append multiple elements in one line of code:

//Adding multiple elements.
cars.push('Mercedes', 'Honda', 'Toyota');

Hopefully, you found this tutorial to be helpful!