Add or append a new item to an array in JavaScript using push() method

By Faruque Ahamed Mollick

In this tutorial, we are going to learn how to append or add a new item to an array using the JavaScript push() method. We will learn with simple example code.

JavaScript array push() method can add any new array item to the end of an existing array.

The simplest syntax of JavaScript push() method is given below:

array.push(newItem);

Well, you can append multiple new items also:

array.push(newItem1, newItem2, newItem3, .......... newItemN);

Now we are going to see a simple example.

Suppose we have an array that contains some city name just you can see it below:

var cities = ["London", "Dubai", "New York", "Jakarta", "Manila"];

Now we want to add a new city in the array. We can do it by using the JavaScript push method just like below:

cities.push("Kolkata");

Now, to better understand let’s run the below HTML code on your browser:



<html>
<body>

<button onclick="addCity()">Add new city</button>
<div id="display_cities"></div>

<script>
var cities = ["London", "Dubai", "New York", "Jakarta", "Manila"];
document.getElementById("display_cities").innerHTML = cities;

function addCity() {
    cities.push("Kolkata");
    document.getElementById("display_cities").innerHTML = cities;
}
</script>

</body>
</html>

In the above HTML code, we have created an array which contains few cities and we display it in a div element. After that, we add new city using JavaScript push method to the cities array. We have used the JavaScript onclick event listener so that the new city will be added after we click the button. We can also add multiple cities by clicking the button just by using the push() method in this way:

cities.push("Kolkata", "Amman", "Istanbul");

 

How to generate a random password in JavaScript?

Validating phone numbers in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *