Skip to content

Foreach push to Array JavaScript | Example code

  • by

The forEach() array method is used to iterate through each item in an array. When using forEach, we have to specify a callback function. Foreach push to Array doesn’t work instead, use for loop in JavaScript.

for (var i = 0; i < a.length; i++) {
    if (a[i] == 1) a.push(5);

Foreach push to Array JavaScript

A simple example code adds value to the array while looping.

<!DOCTYPE html>

    var a = [1,2,3,4];
    var out = [];

      if(value == 1) 




Foreach push to Array JavaScript

forEach() loop to populate an array

we have an array of objects like:

var fruits = [ {name:"banana", weight:150},{name:"apple", weight:95},{name:"orange", weight:160},{name:"kiwi", weight:80} ];

Populate a “heavy_fruits” array with items from the “fruits” array above which weight is > 100. Here is my code:

var heavy_fruits = [];
myfruit = {}; // here's your object

fruits.forEach(function(item,index) {
    if ( item.weight > 100 ) { 
        myfruit ["name"] =;
        myfruit ["weight"] = item.weight; // you modify it's properties

    heavy_fruits.push(myfruit); // you push it to the array

You end up with an array [myfruit, myfruit, myfruit, myfruit].


Do comment if you have any doubts or suggestions on this JS push topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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