In this guide, we will show you how to add a value to the end of a JavaScript array.
In the example below, we will create a JavaScript array and then append new items to it 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:
- Create a JavaScript array containing popular car brand names.
- After that, we add “Honda” and “Toyota” to the end of our array by using the push() method.
- Finally, we log our array to the console.
If you run the example above, you will see that the elements “Honda” and “Toyota” have been successfully added to 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.');
In other words, if you add a value to an array that originally had 3 elements, then the push() method will return 4.
You can also use the push() method to append multiple items in one line of code:
//Adding multiple elements. cars.push('Mercedes', 'Honda', 'Toyota');
In the example above, we were able to provide push() with three values at once.