JavaScript Arrays push


This entry is part 4 of 1 in the series JavaScript Arrays
  • JavaScript Arrays push

Adding Array Elements

You can add elements to an array with the JavaScript array push() method. The push() method adds new items to the end of an array, and returns the new length. To add items at the beginning of an array, use the unshift() method. To remove the last element from the array use the pop method.

If you want to add an element to the beginning of the array you can use unshift.

You can add more than one element at a time. The code in the next code example show you how you can do this.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<p>Another w3schools.com example. The push method appends a new element to an array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
    fruits.push("Lemon");
    document.getElementById("demo").innerHTML = fruits;
}
</script>
</body>
</html>

You can add more than one element to an array with code similar to the following.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi", "Lemon", "Pineapple");

Associative Arrays

JavaScript does not support associative arrays. What are associative arrays? Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes. In JavaScript, arrays always use numbered indexes.

Warning: If you use a named index, JavaScript will redefine the array to a standard object. After that, all array methods and properties will produce incorrect results.

You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.

There is an alternative to using pop(). You can simply get the length of the array and add the element directly. Example code is in the post called JavaScript Arrays Append using Length.

Pushing Objects

<!DOCTYPE html>
<html>
<body>
<script>
// ADD to an array of objects with the push() method.
// Output is sent to the browser console.
//
// This code demonstrates an array of objects that
// needs to be increased in size by two objects.
var fruits = [
  { name: "apple", value: 7 },
  { name: "banana", value: 3 },
  { name: "cherry", value: 9 }
];
// provided by user
var itemName = 'durian';
var itemValue = 1;

fruits.forEach(function(item, index){
    console.log(index + ' => ' + item.name + " " + item.value);
})

fruits.push( {name: itemName, value: itemValue} );
fruits.push( {name: 'elderberry', value: 5} );

console.log("After pushing two fruits, the items are:");
fruits.forEach(function(item, index){
    console.log(index + ' => ' + item.name + " " + item.value);
})
</script>
</body>
</html>