Add With Length Property

As explained earlier in this tutorial, the length property provides an easy way to append new elements to an array without using the push() method:

HTML file: Displayed by browser:
<body>
<h4>Original array:</h4>
<p id="demo"></p>
<hr />
<h4>Add a new element to the array:</h4>
<button onclick="myFunction()">Try it</button>
<p id="demo1"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
    fruits[fruits.length] = "Kiwi";   // Adds Kiwi
    document.getElementById("demo1").innerHTML = fruits;
}
</script>
</body>

Original array:


Add a new element to the array:


BackTable of ContentsNext