JavaScript push(): Add a New Element at the End of an Array

The JavaScript push() method is used to add a new element at the end of an array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      const cities = ["Tokyo", "Bangkok", "Dubai", "Berlin"];
      cities.push("Frankfurt");
      document.getElementById("xyz").innerHTML = cities;
   </script>
   
</body>
</html>
Output

The push() function is used in this code to add an element to the end of the "cities" array.

cities.push("Frankfurt");

The string "Frankfurt" is appended to the end of the "cities" array, making it the fifth element.

The innerHTML property of an HTML element with ID "xyz" is set to the contents of the cities array after the new element is added.

document.getElementById("xyz").innerHTML = cities;

The HTML element with ID "xyz" is chosen in this case using the document.getElementById() function. The cities array value, which is a string with each of the cities array's elements separated by commas, is then set as the value of the innerHTML property.

JavaScript push() Syntax

The syntax of the push() method in JavaScript is:

array.push(elementOne, elementTwo, elementThree, ..., elementN)

A minimum of one element is required.

Advantages of the push() function in JavaScript

Disadvantages of the push() function in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!