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:

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:

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:

Hopefully, you found this tutorial to be helpful!

Facebook Comments