Take a look at the code below:
- 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.