JavaScript Arrays Append using Length


Here is some code from wschools.com showing us how to add an element to the end of an array without using the push() method. We can get the length of the array and use that as the index value.

<!DOCTYPE html>
<html>
<body>
<p>The length property provides an easy way to append new elements to an array without using the push() method.</p>
<button onclick="myFunctionKiwi()">Add Kiwi</button>
<button onclick="myFunctionCherry()">Add Cherry</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunctionKiwi() {
    fruits[fruits.length] = "Kiwi";
    document.getElementById("demo").innerHTML = fruits;
}
function myFunctionCherry() {
    fruits[fruits.length] = "Cherry";
    document.getElementById("demo").innerHTML = fruits;
}
</script>
</body>
</html>

Leave a comment

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