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
Answer from Christian C. Salvadó on Stack Overflow
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.

🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Loops_and_iteration
Loops and iteration - JavaScript - MDN Web Docs - Mozilla
The for...of statement creates a loop Iterating over iterable objects (including Array, Map, Set, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
Discussions

I have an array [1,2,3,4,5]. I can use foreach to loop through it and add it to the DOM as list items. How can I modify the loop to loop through the numbers in a random order every time instead of adding the list items in the same order as the array items?
Both these suggestions are the same at their core, but you can either pre-shuffle the array, or shuffle the array of indices and iterate over that A good enough way of shuffling an array is array.sort(()=>Math.random() - 0.5) More on reddit.com
🌐 r/learnjavascript
9
29
October 15, 2021
Loop through big array in JS
100k elements is not a big number, JS is pretty fast. Benchmark code: Gist Results on Node 18 LTS: Running "Loop through array of 100k numbers" suite... Progress: 100% for: 931 ops/s, ±0.82% | 1.9% slower for..of: 879 ops/s, ±0.27% | 7.38% slower forEach: 476 ops/s, ±0.30% | slowest, 49.84% slower reduce: 641 ops/s, ±0.16% | 32.46% slower while: 949 ops/s, ±0.19% | fastest Finished 5 cases! Fastest: while Slowest: forEach Results for Node 19 (current): Running "Loop through array of 100k numbers" suite... Progress: 100% for: 920 ops/s, ±0.59% | 22.1% slower for..of: 848 ops/s, ±0.38% | 28.2% slower forEach: 474 ops/s, ±0.25% | slowest, 59.86% slower reduce: 1 181 ops/s, ±17.27% | fastest while: 918 ops/s, ±0.44% | 22.27% slower Finished 5 cases! Fastest: reduce Slowest: forEach As you can see, all the result are of the same order of magnitude, and run through the entire array hundreds times a second on may old laptop. They also differ for different engines, and different versions of the same engines. Use whatever is more readable in your case. Any of these should be fine for most cases. More on reddit.com
🌐 r/learnjavascript
2
3
January 13, 2023
[JavaScript] All multiples of 3 and 5 below a given number
Isn't there a way more efficient way to do this? Let n be the number, compute n/3 and n/5 using integer division (i.e. round down, floor whatever you want to call it) - in Python this can be done by doing int(n/3) and int(n/5) Then calculate the multiples of 3 up to int(n/3) and the multiples of 5 up to int(n/5) adding them to a list. Use a for loop for this - you could even store the numbers 1 to n/3 (or n/5) in a vector to vectorise (which IIRC benefits from SIMD or use some other parallelisation thing like multiple cores) if n was really big. Both solutions are O(n) but using integer division and calculating the multiples directly has a much smaller leading constant than brute force comparisons. More on reddit.com
🌐 r/learnprogramming
19
3
March 8, 2015
[Java] Trying to fill an array with unique random numbers.
So you need to fill an array with unique random numbers. You need an array. You need to loop through each position of the array. At each position, generate a random number Try it with only One loop. If you get stuck, feel free to let me know. More on reddit.com
🌐 r/learnprogramming
7
1
November 15, 2014
🌐
W3Schools
w3schools.com › js › js_array_iteration.asp
JavaScript Array Iteration
const numbers = [45, 4, 9, 16, 25]; const over18 = numbers.filter(myFunction); function myFunction(value) { return value > 18; } Try it Yourself » · The reduce() method runs a function on each array element to produce a single value.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-loop-through-an-array-in-javascript-js-iterate-tutorial
How to Loop Through an Array in JavaScript – JS Iterate Tutorial
November 7, 2024 - Then the number will continue to increase and output each element until the condition we set returns false, indicating that we have reached the end of the array. When i = 6, the condition will no longer be executed because the array's last index is 5. The do...while loop is nearly identical to the while loop, except that it executes the body first before evaluating the condition for subsequent executions.
🌐
W3docs
w3docs.com › javascript
How to Loop through an Array in JavaScript
Whenever you want to iterate over an array, an straight-forward way is to have a for loop iterating over the array's keys, which means iterating over zero to the length of the array.
🌐
freeCodeCamp
freecodecamp.org › news › loop-through-arrays-javascript
How to Loop Through Arrays in JavaScript
October 31, 2023 - We achieve this by first using the filter method to create a new array evenNumbers containing only the even numbers from the numbers array. Then, we use the map method to double each element in the evenNumbers array, resulting in the ...
🌐
Sentry
sentry.io › sentry answers › javascript › loop over an array in javascript
Loop over an array in JavaScript | Sentry
January 30, 2023 - Modern JavaScript provides the for...of statement as a simple way to loop over array items. const numbers = [1, 2, 3]; for (const number of numbers) { console.log(number); } // output: // 1 // 2 // 3
Find elsewhere
🌐
CoreUI
coreui.io › blog › how-to-loop-through-an-array-in-javascript
How to loop through an array in JavaScript · CoreUI
July 23, 2024 - It’s a straightforward way to loop through an array and access each element using array indexes. const numbers = [1, 2, 3, 4, 5] for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]) } Introduced in ES6, the for…of loop iterates directly over array elements.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › for...of
for...of - JavaScript | MDN - MDN Web Docs
The for...of loop iterates and logs values that iterable, as an array (which is iterable), defines to be iterated over.
🌐
W3Schools
w3schools.com › js › js_loop_for.asp
JavaScript for Loop
For Loops can execute a block of code a number of times.
🌐
Reddit
reddit.com › r/learnjavascript › i have an array [1,2,3,4,5]. i can use foreach to loop through it and add it to the dom as list items. how can i modify the loop to loop through the numbers in a random order every time instead of adding the list items in the same order as the array items?
r/learnjavascript on Reddit: I have an array [1,2,3,4,5]. I can use foreach to loop through it and add it to the DOM as list items. How can I modify the loop to loop through the numbers in a random order every time instead of adding the list items in the same order as the array items?
October 15, 2021 -

Hi

So let's say I have an array:

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

And I'm using this function to add the array items in the DOM as list items:

const ul = document.querySelector('#ul')

const addNumbersToTheDOM = () => {
    numbers.forEach(number => {
        ul.innerHTML += `<li>${number}</li>`
    })
}

addNumbersToTheDOM()

The result obviously is:

<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>

I'm curious to know how to output the numbers in a random order every time the function runs instead of 1,2,3,4,5 (i.e. the order the items are in the array)?

Thanks

🌐
Reddit
reddit.com › r/learnjavascript › loop through big array in js
r/learnjavascript on Reddit: Loop through big array in JS
January 13, 2023 -

Let's say I have a big data array filled with numbers. Like 100 000 of them.

Which is the best way to "loop through" the entire object?

I've been reading about multithreading, web workers and so on. Also if I should use .reduce instead of for-loops with bigger data.

Is those the best ways to go, theoretically?

for now I use a for loop like this:

for(let i = 0; i < array.length; i++) {

// Do stuff

}

... But I don't think it's the best solution

🌐
Flexiple
flexiple.com › javascript › javascript-loop-array
How to Loop Through an Array in JavaScript – JS Iterate Tutorial - Flexiple
Using the map() method in JavaScript is a powerful function used to loop through an array and apply a function to every element of the array. This method generates a new array containing the results of the function application, ensuring that ...
🌐
Exercism
exercism.org › tracks › javascript › concepts › array-loops
Array Loops in JavaScript on Exercism
The most basic and usually very performant way to iterate over an array is to use a for loop, see Concept For Loops. const numbers = [6.0221515, 10, 23]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } // => 6.0221515 // ...
🌐
Love2Dev
love2dev.com › blog › javascript-for-loop-foreach
Looping JavaScript Arrays Using for, forEach & More 👨‍💻
Referencing items in arrays is ... (initialization; condition; final expression) { // code to be executed} As you can see the for loop statement uses three expressions: the initialization, the condition, and the final expres...
🌐
Alma Better
almabetter.com › bytes › tutorials › javascript › array-iteration-in-javascript
Array Iteration in JavaScript
November 24, 2024 - The reduce() method then returns the final value of the accumulator, which is the sum of all the numbers. Array Iteration in JavaScript is a fundamental operation in JavaScript that allows developers to access and manipulate the elements of an array. It is a crucial process that enables developers to perform tasks such as searching for specific items, filtering out elements, and transforming data. There are several techniques for iterating over arrays, including using for loops, for...of loops, and the built-in forEach method.
🌐
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
🌐
Medium
medium.com › @jacquiedesrosiers › mastering-javascript-5-ways-to-loop-through-an-array-6ed1b58f55d4
Mastering JavaScript: 5 Ways to Loop Through an Array | by jacquie d.r. | Medium
May 13, 2023 - This blog will explore some of the methods we can use to iterate through an array in JavaScript: the simple for loop, the while loop, and the methods:forEach, map, and filter.
🌐
Bonsaiilabs
bonsaiilabs.com › loop-array-javascript
How to loop through an array in JavaScript? - bonsaiilabs
One of the parameters of this function is the current element in the array. So we pass through this function an argument channel, which is nothing but the current social channel. When this function executes, it logs every channel on the console. We'll run it again, and the same result. Now the third approach would be to use for-of, which gives you the direct access to the element in an iterable. Unlike the simple for loop, we looked at the for-of loop came from ES6 specification.