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
🌐
W3Schools
w3schools.com › js › js_loop_while.asp
JavaScript While Loop
A while loop is much the same as a for loop, with statement 1 and statement 3 omitted. Uses a for loop to collect the car names from the cars array:
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Loops_and_iteration
Loops and iteration - JavaScript - MDN Web Docs - Mozilla
When you use break without a label, ... do-while, for, or switch immediately and transfers control to the following statement. When you use break with a label, it terminates the specified labeled statement. The syntax of the break statement looks like this: ... The first form of the syntax terminates the innermost enclosing loop or switch. The second form of the syntax terminates the specified enclosing labeled statement. The following example iterates through the elements in an array until it finds ...
Discussions

Loop through an array in JavaScript - Stack Overflow
Note that some interpreters (e.g. ... by the loop. While caching the length is still nice, it may not provide a speed boost when your code is being invoked enough times to actually make a difference. 2012-06-04T16:29:24.937Z+00:00 ... You can use map, which is a functional programming technique that's also available in other languages like Python and Haskell. ... In general func would take one parameter, which is an item of the array. But in the case of JavaScript, it can take ... More on stackoverflow.com
🌐 stackoverflow.com
While-loop with arrays in JavaScript - Stack Overflow
I need help with this code in Js. this example : let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"]; let index = 0; let counter = 0;... More on stackoverflow.com
🌐 stackoverflow.com
html - Javascript While Looping Through Array And Outputting in .innerhtml - Stack Overflow
I'm brand new to Javascript and teaching myself. I'm trying to setup a function that will write each of the elements of the array AmericanCars with a space between the elements. I have it workin... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
javascript - Is it good practice to use array.pop() assignment in a while loop condition? - Software Engineering Stack Exchange
The first element in the array will be missed. Why? The first element is zero, which when used in an assignment statement, returns the value zero, which is treated as false by the while loop, meaning the while loop stops before processing the last item on the "stack", or rather the first element ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
September 8, 2016
🌐
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 - 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.
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.

🌐
Stack Overflow
stackoverflow.com › questions › 69315873 › while-loop-with-arrays-in-javascript
While-loop with arrays in JavaScript - Stack Overflow
You should increase the index at the end of the loop, otherwise you skip the first element and overshoot the last one. while(index < friends.length){ if ( typeof friends[index] === "number"){ continue; } if (friends[index][counter] === "A"){ continue; } console.log(friends[index]); index++; } A better way to iterate through the array would be a for...of loop, so you won't have to use the index at all.
🌐
CoreUI
coreui.io › blog › how-to-loop-through-an-array-in-javascript
How to loop through an array in JavaScript · CoreUI
July 23, 2024 - Arrays in JavaScript are flexible and can store various data types, such as numbers, strings, objects, and even other arrays. The while loop evaluates a specified condition and executes the loop body as long as the condition is true.
Find elsewhere
Top answer
1 of 2
10

It is not necessarily wrong if the code does what it is supposed to do, however, decisions such as this can be a matter of taste or opinion in personally written code. Conversely, avoiding this particular arrangement of logic may be a requirement of an employer.

Here are the things to consider.

  1. Do you understand what the code is doing?
  2. Is anyone else expected to read the code and understand what it is doing, and will it be relatively easy for them to read and understand what the code is doing?
  3. Will the code be used as part of the development code on a project for a group or organization that implements Programming Style guidelines?

Edit

To be more specific, here are some pros and cons using the code in your example.

Pros

  • In specific use cases, such as an array which is guaranteed to contain objects or other "truthy" values, this way is concise, doubling as a conditional statement and an assignment statement.

Cons

  • If the array contains undefined, null, 0, false, NaN, "" or has "holes" in it, this way will fail.

"Holes" means when the array has a length greater than 0 and some (or all) of the elements of the array have not been assigned a value.

"Truthy" means values that do not evaluate to false ( see the cons ). Do not forget NaN or "", I almost just did.

The code in your example already contains a bug. The first element in the array will be missed. Why? The first element is zero, which when used in an assignment statement, returns the value zero, which is treated as false by the while loop, meaning the while loop stops before processing the last item on the "stack", or rather the first element in the array.

2 of 2
4

If the intention is to process the array like a queue or a stack, wherein items are removed as they're processed, yes. This is a pretty standard approach.

In fact, you'll sometimes see this sort of loop for tree traversals where stack overflows, or the need to pause and resume, are a potential problem in the recursive solution.

🌐
Stack Overflow
stackoverflow.com › questions › 55302857 › using-a-while-loop-to-loop-over-an-array
javascript - Using a while loop to loop over an array - Stack Overflow
Just for fun, here is an alternative to the other answers that may give you some additional insight into how functions, loops, and arrays work. const facts = [ "He was the last Beatle to learn to drive", "He was never a vegetarian", "He was a choir boy and boy scout", "He hated the sound of his own voice" ]; const exclamation = (arr) => { let i = arr.length; while (i) { i--; arr[i] += '!!!'; } return arr; }; const loudfacts = exclamation(facts); console.log(loudfacts); /* [ "He was the last Beatle to learn to drive!!!", "He was never a vegetarian!!!", "He was a choir boy and boy scout!!!", "He hated the sound of his own voice!!!"
🌐
The Odin Project
theodinproject.com › lessons › foundations-loops-and-arrays
Loops and Arrays | The Odin Project
Some of them will contain examples ... that arrays are just lists of items. Read MDN’s Looping Code. It’s a longer one, but make sure you tackle the exercises near the bottom of the page. Once again, same info, slightly different context from JavaScript.info’s “Loops: While and For”. ...
🌐
Launch School
launchschool.com › books › javascript › read › loops_iterating
Loops in JavaScript - performing repeated operations on a data set
This program functions in the same way as the version that uses while. The difference is that we initialize the index variable, specify the loop condition, and increment the index variable all on the same line. When JavaScript runs this loop, it follows this sequence: Declare and initialize the index variable to 0. If index is not less than the array length, go to step 6.
🌐
W3docs
w3docs.com › javascript
How to Loop through an Array in JavaScript
You define a variable like i in for (let i in arr), and in each iteration, the variable i will become equal to a key in arr. Then you will be able to select the desired array element with something like arr[i]. See an example below.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › iterate-over-array-javascript
JavaScript - Iterate Over an Array - GeeksforGeeks
It is similar to loops in other languages like C/C++, Java, etc. ... A while loop in JavaScript is a control flow statement that allows the code to be executed repeatedly based on the given boolean condition.
Published   January 15, 2026
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › while
while - JavaScript - MDN Web Docs - Mozilla
July 8, 2025 - After completing the third pass, the condition n < 3 is no longer true, so the loop terminates. In some cases, it can make sense to use an assignment as a condition. This comes with readability tradeoffs, so there are certain stylistic recommendations that would make the pattern more obvious for everyone. Consider the following example, which iterates over a document's comments, logging them to the console. ... const iterator = document.createNodeIterator(document, NodeFilter.SHOW_COMMENT); let currentNode; while (currentNode = iterator.nextNode()) { console.log(currentNode.textContent.trim()); }
🌐
Attacomsian
attacomsian.com › blog › javascript-loops
How to loop through an array in JavaScript
June 10, 2023 - do...while executes a code block at least once, then repeats it as long as a condition remains true. The for loop is commonly used to iterate over arrays and NodeLists in JavaScript.
🌐
W3Schools
w3schools.com › js › js_loop_for.asp
JavaScript for Loop
When let is used to declare the i variable in a loop, the i variable will only be visible within the loop. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript while loop
JavaScript while Loop By Examples
November 15, 2024 - let mountains = ['Mount Everest', 'K2', 'Lhotse', 'Kangchenjunga'];Code language: JavaScript (javascript) Second, declare and initialize a loop variable (i) to zero: ... Third, run the loop as long as the loop variable (i) is less than the number of elements in the mountains array: while (i < mountains.length) {Code language: JavaScript (javascript)
🌐
Programiz
programiz.com › javascript › while-loop
JavaScript while and do...while Loop (with Examples)
JavaScript for... of Loop ... The while loop repeatedly executes a block of code as long as a specified condition is true.
🌐
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 statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the arguments object, generators produced by generator functions, and user-defined iterables.