Use forEach its a built-in array function. Array.forEach():

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});
Answer from Dory Zidon on Stack Overflow
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Statements โ€บ for...of
for...of - JavaScript | MDN - MDN Web Docs
The for...in loop logs only enumerable properties of the iterable object. It doesn't log array elements 3, 5, 7 or "hello" because those are not properties โ€” they are values. It logs array indexes as well as arrCustom and objCustom, which are actual properties.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Statements โ€บ for...in
for...in - JavaScript | MDN - MDN Web Docs
It is better to use a for loop with a numeric index, Array.prototype.forEach(), or the for...of loop, because they will return the index as a number instead of a string, and also avoid non-index properties. If you only want to consider properties attached to the object itself, and not its ...
Discussions

javascript - How to loop through an array containing objects and access their properties - Stack Overflow
I want to cycle through the objects contained in an array and change the properties of each one. If I do this: for (var j = 0; j More on stackoverflow.com
๐ŸŒ stackoverflow.com
How can I loop through a JavaScript object array? - Stack Overflow
The only credible reason not to use for..in with an Array is that the properties may not be returned in the expected order. Otherwise, it's no better or worse than using for..in on any other Object (unexpected properties, properties from the [[Prototype]], etc.). ... It appears you may just have missed the "messages" property in the data, so the loop ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Loop through an array in JavaScript - Stack Overflow
Meaning that there actually is a value at each index in the array. However, I found that in practice I hardly ever use sparse arrays in JavaScript... In such cases it's usually a lot easier to use an object as a map/hashtable. If you do have a sparse array, and want to loop over 0 .. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to loop through every array inside an array of arrays (and objects) with unknown depth?
Here is the template for a queueing method you can use. It can be faster than recursion and doesn't run adrift of the issue with recursion depth. const queue = [mainArray]; while (true) { if (queue.length < 1) break; let current = queue.shift(); for (let x in current){ if (Array.isArray(current[x]) || typeof (current[x]) === "object") { queue.push(current[x])} else console.log(current[x]); } } More on reddit.com
๐ŸŒ r/learnjavascript
4
1
November 9, 2023
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Array โ€บ forEach
Array.prototype.forEach() - JavaScript - MDN Web Docs
const logArrayElements = (element, index /*, array */) => { console.log(`a[${index}] = ${element}`); }; // Notice that index 2 is skipped, since there is no item at // that position in the array. [2, 5, , 9].forEach(logArrayElements); // Logs: // a[0] = 2 // a[1] = 5 // a[3] = 9 ยท The following ...
Top answer
1 of 16
511

Use forEach its a built-in array function. Array.forEach():

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});
2 of 16
322

Some use cases of looping through an array in the functional programming way in JavaScript:

1. Just loop through an array

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
});

Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.

2. Check if any of the elements in an array pass a test

const people = [
    {name: 'John', age: 23}, 
    {name: 'Andrew', age: 3}, 
    {name: 'Peter', age: 8}, 
    {name: 'Hanna', age: 14}, 
    {name: 'Adam', age: 37}];

const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true

3. Transform to a new array

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.

4. Sum up a particular property, and calculate its average

const myArray = [{x:100}, {x:200}, {x:300}];

const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300

const average = sum / myArray.length;
console.log(average); // 200

5. Create a new array based on the original but without modifying it

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => {
    return {
        ...element,
        x: element.x * 2
    };
});

console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]

6. Count the number of each category

const people = [
    {name: 'John', group: 'A'}, 
    {name: 'Andrew', group: 'C'}, 
    {name: 'Peter', group: 'A'}, 
    {name: 'James', group: 'B'}, 
    {name: 'Hanna', group: 'A'}, 
    {name: 'Adam', group: 'B'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
    }
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}

7. Retrieve a subset of an array based on particular criteria

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}] 

Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.

8. Sort an array

const people = [
  { name: "John", age: 21 },
  { name: "Peter", age: 31 },
  { name: "Andrew", age: 29 },
  { name: "Thomas", age: 25 }
];

let sortByAge = people.sort(function (p1, p2) {
  return p1.age - p2.age;
});

console.log(sortByAge);

9. Find an element in an array

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.

References

  • Array.prototype.some()
  • Array.prototype.forEach()
  • Array.prototype.map()
  • Array.prototype.filter()
  • Array.prototype.sort()
  • Spread syntax
  • Array.prototype.find()
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_array_iteration.asp
JavaScript Array Iteration
Object Path Object Intro Object Properties Object Methods Object this Object Display Object Constructors ... Temporal Study Path Temporal Intro Temporal vs Date Temporal Duration Temporal Instant Temporal PlainDateTime Temporal PlainDate Temporal PlainYearMonth Temporal PlainMonthDay Temporal PlainTime Temporal ZonedDateTime Temporal Now Temporal Arithmetic Temporal Formats Temporal Mistakes Temporal Migrate Temporal Reference ... JS Arrays JS Array Methods JS Array Search JS Array Sort JS Array Iterations JS Array Reference JS Array Const
๐ŸŒ
Medium
medium.com โ€บ @francois.barrailla โ€บ javascript-iterate-over-array-values-and-indexes-using-a-for-of-loop-106a58972b24
JavaScript: Iterate over array values and indexes using a for-of loop | by Franรงois Barrailla | Medium
July 8, 2020 - You can easily iterate through the values AND indexes of an array thanks to the Array.prototype.entries function that will transform the array into a collection of entries. ... Each entry is an array of two values: the first one is the index ...
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-loop-through-an-array-containing-multiple-objects-and-access-their-properties-in-javascript
How to Traverse Array of Objects and Access the Properties in JavaScript? - GeeksforGeeks
July 23, 2025 - ... const a = [ {name: 'Saritha', sub: 'Maths'}, {name: 'Sarthak', sub: 'Science'}, {name: 'Sneha', sub: 'Social'} ] a.forEach(teacher => { for (let value in teacher) { console.log(`${teacher[value]}`) } }) ... The forEach() method executes ...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ loop-through-arrays-javascript
How to Loop Through Arrays in JavaScript
October 31, 2023 - The loop starts at the first element (index 0), which is "apple," and iterates through each subsequent element, printing them one by one until it reaches the end of the array. The forEach method is a built-in JavaScript method for arrays that ...
๐ŸŒ
Mozilla
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Guide โ€บ Loops_and_iteration
Loops and iteration - JavaScript - MDN Web Docs - Mozilla
For an object car with properties make and model, result would be: ... Although it may be tempting to use this as a way to iterate over Array elements, the for...in statement will return the name of your user-defined properties in addition to the numeric indexes. Therefore, it is better to use a traditional for loop with a numeric index when iterating over arrays, because the for...in statement iterates over user-defined properties in addition to the array elements, if you modify the Array object (such as adding custom properties or methods).
๐ŸŒ
CoreUI
coreui.io โ€บ blog โ€บ how-to-loop-through-an-array-in-javascript
How to loop through an array in JavaScript ยท CoreUI
July 23, 2024 - The forโ€ฆin loop iterates over the enumerable properties of an object, but it can also be used for arrays. However, itโ€™s not recommended for arrays due to potential issues with array indexes and prototype properties.
Top answer
1 of 16
5293

Three main options:

  1. for (var i = 0; i < xs.length; i++) { console.log(xs[i]); }
  2. xs.forEach((x, i) => console.log(x));
  3. for (const x of xs) { console.log(x); }

Detailed examples are below.


1. Sequential for loop:

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    console.log(myStringArray[i]);
    //Do something
}

Pros

  • Works on every environment
  • You can use break and continue flow control statements

Cons

  • Too verbose
  • Imperative
  • Easy to have off-by-one errors (sometimes also called a fence post error)

2. Array.prototype.forEach:

The ES5 specification introduced a lot of beneficial array methods. One of them, the Array.prototype.forEach, gave us a concise way to iterate over an array:

const array = ["one", "two", "three"]
array.forEach(function (item, index) {
  console.log(item, index);
});

Being almost ten years as the time of writing that the ES5 specification was released (Dec. 2009), it has been implemented by nearly all modern engines in the desktop, server, and mobile environments, so it's safe to use them.

And with the ES6 arrow function syntax, it's even more succinct:

array.forEach(item => console.log(item));

Arrow functions are also widely implemented unless you plan to support ancient platforms (e.g., Internet Explorer 11); you are also safe to go.

Pros

  • Very short and succinct.
  • Declarative

Cons

  • Cannot use break / continue

Normally, you can replace the need to break out of imperative loops by filtering the array elements before iterating them, for example:

array.filter(item => item.condition < 10)
     .forEach(item => console.log(item))

Keep in mind if you are iterating an array to build another array from it, you should use map. I've seen this anti-pattern so many times.

Anti-pattern:

const numbers = [1,2,3,4,5], doubled = [];

numbers.forEach((n, i) => { doubled[i] = n * 2 });

Proper use case of map:

const numbers = [1,2,3,4,5];
const doubled = numbers.map(n => n * 2);

console.log(doubled);

Also, if you are trying to reduce the array to a value, for example, you want to sum an array of numbers, you should use the reduce method.

Anti-pattern:

const numbers = [1,2,3,4,5];
const sum = 0;
numbers.forEach(num => { sum += num });

Proper use of reduce:

const numbers = [1,2,3,4,5];
const sum = numbers.reduce((total, n) => total + n, 0);

console.log(sum);

3. ES6 for-of statement:

The ES6 standard introduces the concept of iterable objects and defines a new construct for traversing data, the for...of statement.

This statement works for any kind of iterable object and also for generators (any object that has a \[Symbol.iterator\] property).

Array objects are by definition built-in iterables in ES6, so you can use this statement on them:

let colors = ['red', 'green', 'blue'];
for (const color of colors){
    console.log(color);
}

Pros

  • It can iterate over a large variety of objects.
  • Can use normal flow control statements (break / continue).
  • Useful to iterate serially asynchronous values.

Cons

  • If you are targeting older browsers, the transpiled output might surprise you.

Do not use for...in

@zipcodeman suggests the use of the for...in statement, but for iterating arrays for-in should be avoided, that statement is meant to enumerate object properties.

It shouldn't be used for array-like objects because:

  • The order of iteration is not guaranteed; the array indexes may not be visited in numeric order.
  • Inherited properties are also enumerated.

The second point is that it can give you a lot of problems, for example, if you extend the Array.prototype object to include a method there, that property will also be enumerated.

For example:

Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];

for (var i in array) {
    console.log(array[i]);
}

The above code will console log "a", "b", "c", and "foo!".

That can be particularly a problem if you use some library that relies heavily on native prototypes augmentation (such as MooTools).

The for-in statement, as I said before, is there to enumerate object properties, for example:

var obj = {
    "a": 1,
    "b": 2,
    "c": 3
};

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
        console.log("prop: " + prop + " value: " + obj[prop])
    }
}

In the above example, the hasOwnProperty method allows you to enumerate only own properties. That's it, only the properties that the object physically has, no inherited properties.

I would recommend you to read the following article:

  • Enumeration VS Iteration
2 of 16
1210

Yes, assuming your implementation includes the for...of feature introduced in ECMAScript 2015 (the "Harmony" release)... which is a pretty safe assumption these days.

It works like this:

// REQUIRES ECMASCRIPT 2015+
var s, myStringArray = ["Hello", "World"];
for (s of myStringArray) {
  // ... do something with s ...
}

Or better yet, since ECMAScript 2015 also provides block-scoped variables:

// REQUIRES ECMASCRIPT 2015+
const myStringArray = ["Hello", "World"];
for (const s of myStringArray) {
  // ... do something with s ...
}
// s is no longer defined here

(The variable s is different on each iteration, but can still be declared const inside the loop body as long as it isn't modified there.)

A note on sparse arrays: an array in JavaScript may not actually store as many items as reported by its length; that number is simply one greater than the highest index at which a value is stored. If the array holds fewer elements than indicated by its length, its said to be sparse. For example, it's perfectly legitimate to have an array with items only at indexes 3, 12, and 247; the length of such an array is 248, though it is only actually storing 3 values. If you try to access an item at any other index, the array will appear to have the undefined value there, but the array is nonetheless is distinct from one that actually has undefined values stored. You can see this difference in a number of ways, for example in the way the Node REPL displays arrays:

> a              // array with only one item, at index 12
[ <12 empty items>, 1 ]
> a[0]           // appears to have undefined at index 0
undefined
> a[0]=undefined // but if we put an actual undefined there
undefined
> a              // it now looks like this
[ undefined, <11 empty items>, 1 ]

So when you want to "loop through" an array, you have a question to answer: do you want to loop over the full range indicated by its length and process undefineds for any missing elements, or do you only want to process the elements actually present? There are plenty of applications for both approaches; it just depends on what you're using the array for.

If you iterate over an array with for..of, the body of the loop is executed length times, and the loop control variable is set to undefined for any items not actually present in the array. Depending on the details of your "do something with" code, that behavior may be what you want, but if not, you should use a different approach.

Of course, some developers have no choice but to use a different approach anyway, because for whatever reason they're targeting a version of JavaScript that doesn't yet support for...of.

As long as your JavaScript implementation is compliant with the previous edition of the ECMAScript specification (which rules out, for example, versions of Internet Explorer before 9), then you can use the Array#forEach iterator method instead of a loop. In that case, you pass a function to be called on each item in the array:

var myStringArray = [ "Hello", "World" ];
myStringArray.forEach( function(s) { 
     // ... do something with s ...
} );

You can of course use an arrow function if your implementation supports ES6+:

myStringArray.forEach( s => { 
     // ... do something with s ...
} );

Unlike for...of, .forEach only calls the function for elements that are actually present in the array. If passed our hypothetical array with three elements and a length of 248, it will only call the function three times, not 248 times. If this is how you want to handle sparse arrays, .forEach may be the way to go even if your interpreter supports for...of.

The final option, which works in all versions of JavaScript, is an explicit counting loop. You simply count from 0 up to one less than the length and use the counter as an index. The basic loop looks like this:

var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
  s = myStringArray[i];
  // ... do something with s ...
}

One advantage of this approach is that you can choose how to handle sparse arrays. The above code will run the body of the loop the full length times, with s set to undefined for any missing elements, just like for..of; if you instead want to handle only the actually-present elements of a sparse array, like .forEach, you can add a simple in test on the index:

var i, s, myStringArray = [ "Hello", "World" ], len = myStringArray.length;
for (i=0; i<len; ++i) {
  if (i in myStringArray) {
    s = myStringArray[i];
    // ... do something with s ...
  }
}

Depending on your implementation's optimizations, assigning the length value to the local variable (as opposed to including the full myStringArray.length expression in the loop condition) can make a significant difference in performance since it skips a property lookup each time through. You may see the length caching done in the loop initialization clause, like this:

var i, len, myStringArray = [ "Hello", "World" ];
for (len = myStringArray.length, i=0; i<len; ++i) {

The explicit counting loop also means you have access to the index of each value, should you want it. The index is also passed as an extra parameter to the function you pass to forEach, so you can access it that way as well:

myStringArray.forEach( (s,i) => {
   // ... do something with s and i ...
});

for...of doesn't give you the index associated with each object, but as long as the object you're iterating over is actually an instance of Array (and not one of the other iterable types for..of works on), you can use the Array#entries method to change it to an array of [index, item] pairs, and then iterate over that:

for (const [i, s] of myStringArray.entries()) {
  // ... do something with s and i ...
}

The for...in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it. But the problem is that it doesn't restrict itself to the numeric property values (remember that even methods are actually just properties whose value is a closure), nor is it guaranteed to iterate over those in numeric order. Therefore, the for...in syntax should not be used for looping through Arrays.

๐ŸŒ
Flexiple
flexiple.com โ€บ javascript โ€บ loop-through-object-javascript
How to loop through objects keys and values in Javascript?
Object.entries() returns an array of an object's enumerable properties in [key, value] pairs. Utilizing these methods simplifies iterating over objects, enabling efficient data manipulation and retrieval. Utilize methods that allow for efficient enumeration and access to iterate through an object's keys and values in JavaScript. The for...in loop offers a simple way to traverse all enumerable properties of an object, enabling you to access each key and its corresponding value directly.
๐ŸŒ
Log4JavaScript
log4javascript.org โ€บ home โ€บ js-framework โ€บ the art of looping through arrays of objects in javascript
JavaScript Loop Through Array of Objects: Master the Art
July 4, 2023 - In JavaScript, arrays are a type ... { console.log(users[i].name, users[i].age, users[i].role); } In the forโ€ฆin loop, i is the index of the current array item....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ iterate-over-array-javascript
JavaScript - Iterate Over an Array - GeeksforGeeks
The for loop in JavaScript is commonly used to iterate through an array. It allows you to process each element one by one using its index. The loop runs from 0 to the length of the array โˆ’ 1. Each iteration executes the code inside the loop.
Published ย  January 15, 2026
๐ŸŒ
Attacomsian
attacomsian.com โ€บ blog โ€บ javascript-iterate-array-of-objects
Loop through an array of objects in JavaScript
June 10, 2023 - In JavaScript, you can loop through an array of objects using the forEach() method combined with the for...in loop.
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_loop_for.asp
JavaScript for Loop
Object Path Object Intro Object Properties Object Methods Object this Object Display Object Constructors ... Temporal Study Path Temporal Intro Temporal vs Date Temporal Duration Temporal Instant Temporal PlainDateTime Temporal PlainDate Temporal PlainYearMonth Temporal PlainMonthDay Temporal PlainTime Temporal ZonedDateTime Temporal Now Temporal Arithmetic Temporal Convertion Temporal Formats Temporal Mistakes Temporal Migrate Temporal Reference ... JS Arrays JS Array Methods JS Array Search JS Array Sort JS Array Iterations JS Array Reference JS Array Const
๐ŸŒ
Medium
medium.com โ€บ @louistrinh โ€บ iterating-through-javascript-objects-and-arrays-for-foreach-and-beyond-e9e6ce5376d3
Iterating Through JavaScript Objects and Arrays: for, forEach, and Beyond | by Louis Trinh | Medium
May 10, 2024 - Iterating Through JavaScript Objects and Arrays: for, forEach, and Beyond ยท for loop: Iterates a specific number of times, often using an index to access elements: const numbers = [1, 4, 7, 2]; for (let i = 0; i < numbers.length; i++) { ...
๐ŸŒ
Medium
medium.com โ€บ @deepakkatarachat โ€บ the-ultimate-guide-to-looping-through-javascript-objects-and-arrays-plain-nested-61435f18ec12
๐Ÿš€ The Ultimate Guide to Looping Through JavaScript Objects and Arrays (Plain & Nested) [Part-1] | by deepak katara | Medium
April 20, 2025 - But itโ€™s not just about knowing how to loop โ€” itโ€™s about choosing the right tool for the job. ... const data = { user: { name: "Bob", address: { city: "NYC", zip: 10001 }, hobbies: ["reading", "gaming"] } }; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } Use Case: Need index, more control (break/continue). for (const fruit of fruits) { console.log(fruit); } Use Case: Clean syntax for simple value iteration. fruits.forEach((fruit, index) => { console.log(index, fruit); });
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ how to loop through every array inside an array of arrays (and objects) with unknown depth?
r/learnjavascript on Reddit: How to loop through every array inside an array of arrays (and objects) with unknown depth?
November 9, 2023 -

Let's say I have an array like this:

mainArray = [
    0: {
        title: "Socials"
        chilren: [
            0 = {id: 1, title: "Twitter"},
            1 = {id: 2, title: "Facebook"},
            2 = {id: 3, title: "YouTube"}
        ]
    },
    1: {
        title: "Forums"
        children: [
            0 = {
                id: 1,
                title: "Car Forums
                children = [
                    MORESUBFOLDERS?,
                    MORESFILES?
                ]
            "},
            2 = {id: 3, title: "tech-forum.com"},
            3 = {id: 4, title: "fitness-forum,com"}
        ]
    },
    n: {...}
];  

This array represents a file structure with an unknown number of subfolders and files, with the main array being the root folder.

As you can see, each object inside the mainArray is a subfolder, these subfolder objects can contain an object representing a file, or an array inside an object representing a new subfolder. These sub-sub-folders can also have files as objects or subfolders as arrays, and this can go on for ever in theory. Obviously in practice there's limited depth, but the idea is to have a single function that traverses the entire data structure and returns something like:

rootFolder: {
    folder1: {
        subfolder1: {
            subfolderN {...}
            subfolderN {...}
            fileN
            fileN
        }
    }
    folderN: {
        subfolderN: {
            subfolderN {...}
            subfolderN {...}
            fileN
            fileN
        }
    }
};  

So I can render this as an HTML nested unordered list.