UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Adding item to an array using push() method - javascript

Demo and code for how to add item to an array using push() in javascript.

by Athil


Posted on 27 Jun 2018 Category: Javascript Views: 1630


Here I am going to show how to add an item to an array using javascript push() method.

DEMO

 var arrayname = ["Car", "Bike", "Truck", "Scooter"];
            arrayname.push("Train");

Here arrayname is the name of the array and it pushes value "Trian" to existing array. This will result in new array ["Car", "Bike", "Truck", "Scooter", "Train"], That means the new item will be added after the last index of the array.

Full Demo code HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Demo for array push javascript</title>
</head>
      <h1>Demo for array push javascript </h1>
    <button onclick="addtoarray();">Add to array</button>
         <div id="add" style="margin-top:200px;">
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
   

<body>
  
    

</body>
</html>

Javascript


        function addtoarray()
        {
            var arrayname = ["Car", "Bike", "Truck", "Scooter"];
            arrayname.push("Train");
            alert(JSON.stringify(arrayname));
        }

 



Leave a Comment:


Click here to register

Popular articles