The push() Method

The push(element) method adds a new element to an array (at the end). The push() method returns the new array length (how many elements are in the array):

HTML file: Displayed by browser:
<body>
<h4>The original, untouched array:</h4>
<p id="demo"></p>
<hr />
<h4>The push method appends new elements to the end of an array:</h4>
<button onclick="myPushing()">Push it In</button>
<p id="demo1"></p>
<hr />
<h4>The push method returns the number of items in the array:</h4>
<button onclick="myCount()">How Many Items?</button>
<p id="demo2"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myPushing() {
    fruits.push("Kiwi");
    document.getElementById("demo1").innerHTML = fruits;
}
function myCount() {
    document.getElementById("demo2").innerHTML = fruits.push();
}
</script>
</body>

The original, untouched array:


The push method appends new elements to the end of an array:


The push method returns the number of items in the array:

Note to myself: Another challenging piece of coding! At first, I tried to use "var x = fruits.push()" but that brought up 4. Using "var x = fruits.push("Kiwi")" only put "Kiwi" into my array again, giving me 6 items, but still counting 1 less (giving me 5). I found this coding worked as it should so I guess this is just another weird one! Popping and pushing is not my thing, I guess.

BackTable of ContentsNext