🌐
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 ...
🌐
W3Schools
w3schools.com › js › js_loop_forof.asp
JavaScript For Of
The JavaScript for of statement loops through the values of an iterable object.
🌐
W3Schools
w3schools.com › js › js_loop_for.asp
JavaScript for Loop
The for statement creates a loop with 3 optional expressions: for (exp 1; exp 2; exp 3) { // code block to be executed } exp 1 is executed (one time) before the execution of the code block.
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Loops_and_iteration
Loops and iteration - JavaScript - MDN Web Docs - Mozilla
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. ... The initializing expression initialization, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-for-of-loop
JavaScript for...of Loop - GeeksforGeeks
August 5, 2025 - The JavaScript for...of loop is a modern, iteration statement introduced in ECMAScript 2015 (ES6).
🌐
DigitalOcean
digitalocean.com › community › tutorials › for-loops-for-of-loops-and-for-in-loops-in-javascript
JavaScript For Loops | DigitalOcean
August 26, 2021 - In this tutorial, we will learn ... elements of the JavaScript programming language. The for statement is a type of loop that will use up to three optional expressions to implement the repeated execution of a code block....
🌐
Programiz
programiz.com › javascript › for-of
JavaScript for... of Loop
The for..of loop in JavaScript allows you to iterate over iterable objects (arrays, sets, maps, strings etc).
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › for
for - JavaScript | MDN - MDN Web Docs - Mozilla
The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-loops-explained-for-loop-for
JavaScript Loops Explained: For Loop, While Loop, Do...while Loop, and More
February 15, 2020 - Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true or false. A loop will continue running until the defined condition returns false. for Loop Syntax for (initialization; condition; ...
Find elsewhere
🌐
Mimo
mimo.org › glossary › javascript › for-loops
JavaScript For Loop: Efficient Iteration in JavaScript
The for of loop simplifies iterating through an arr, making code cleaner. JavaScript's array forEach() method is another form of loop that executes a function once per array element.
🌐
Exploring JS
exploringjs.com › es6 › ch_for-of.html
17. The for-of loop
for-of is a new loop in ES6 that replaces both for-in and forEach() and supports the new iteration protocol.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript for…of loop
Introduction to JavaScript for...of Loop in ES6
October 6, 2023 - let scores = [80, 90, 70]; for (let score of scores) { score = score + 5; console.log(score); }Code language: JavaScript (javascript) ... In this example, the for...of iterates over every element of the scores array. It assigns the element of the scores array to the variable score in each iteration. If you don’t change the variable inside the loop, you should use the const keyword instead of the let keyword as follows:
🌐
Medium
medium.com › @abhishekprasadkashyap › the-new-for-of-loop-a-cleaner-way-to-iterate-in-javascript-3a41c9e3c2c4
The New for...of Loop: A Cleaner Way to Iterate in JavaScript | by Abhishek Prasad | Medium
February 9, 2025 - The for...of loop is used to iterate over the values of an iterable object, meaning it loops through each element directly without needing to track an index.
🌐
Programiz
programiz.com › javascript › for-loop
JavaScript for loop (with Examples)
In JavaScript, the for loop is used for iterating over a block of code a certain number of times, or to iterate over the elements of an array.
🌐
daily.dev
daily.dev › home › blog › get into tech › understanding javascript for of with index
Understanding Javascript for of with index
December 22, 2025 - When you use the for...of loop in JavaScript, it's great for going through items in a list or characters in a string one by one. But it doesn't automatically tell you where you are in the list or string (like, which number item you're on).
Top answer
1 of 12
1229

for…in iterates over property names, not values (and did so in an unspecified order up until ES2020*). You shouldn’t use it to iterate over arrays. For them, there’s ES6’s Array.prototype.entries, which now has support across current browser versions:

const myArray = [123, 15, 187, 32];

for (const [i, value] of myArray.entries()) {
  console.log(`${i}: ${value}`);
}

// 0: 123
// 1: 15
// 2: 187
// 3: 32
.as-console-wrapper { max-height: 100% !important; top: 0; border-top: 0 !important; }

Or, for extended compatibility with older browsers, there’s ES5’s forEach method that passes both the value and the index to the function you give it:

myArray.forEach(function (value, i) {
  console.log('%d: %s', i, value);
});

For iterables in general (where you would use a for…of loop rather than a for…in), iterator helpers are now in the language. You can use Iterator.prototype.forEach to iterate over an entire iterable with an index:

function* fibonacci() {
  let a = 0;
  let b = 1;

  for (;;) {
    yield a;
    [a, b] = [b, a + b];
  }
}

fibonacci().take(10).forEach((x, i) => {
  console.log(`F_${i} = ${x}`);
});
.as-console-wrapper { max-height: 100% !important; top: 0; border-top: 0 !important; }

More generally, Iterator#map can associate the values yielded by an iterator with their indexes:

fibonacci().map((x, i) => [i, x])

Not every iterable (or iterator!) is an Iterator, but you can convert every iterable to an Iterator with Iterator.from.

Without support for iterator helpers, you can use a generator function instead:

function* enumerate(iterable) {
  let i = 0;

  for (const x of iterable) {
    yield [i, x];
    i++;
  }
}

for (const [i, obj] of enumerate(myArray)) {
  console.log(i, obj);
}

If you actually did mean for…in – enumerating properties – you would need an additional counter. Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.

* The order is still unspecified under certain circumstances, including for typed arrays, proxies, and other exotic objects, as well as when properties are added or removed during iteration.

2 of 12
494

In ES6, it is good to use a for... of loop. You can get index in for... of like this

for (let [index, val] of array.entries()) {
  // your code goes here    
}

Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.

Top answer
1 of 2
21

A bit of backnowledge to explain your question:

In Javascript, Objects (among these are Arrays) store properties in key-value pairs. That means that each assigned value has a key (the property name) to access it. For example in

person[name] = 'Tom'

person is the Object, name the key and 'Tom' the corresponding value.

Arrays use indices (i.e. numbers) as keys:

array[5] = 10

Now, keep that in mind in the following explanation.

Let's start with the traditional for loop:

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

This way of iterating over an array is the oldest of the bunch (as long as you are not using while-loops) You'll find a corresponding way of writing a for loop in pretty much any (imperative) programming language. You'll notice, it is very explicit in the way it works. E.g. you could change the break-condition i < array.length to something else (e.g. i < array.length-1 for skipping the last position), or the step i++ (e.g. to i+=2), or start at a different index (e.g. let i = 5). You can iterate backwards instead of forwards through the array, if you want. Pretty much anything you can do in another for loop, you can do in this kind as well, if you know how.

Inside the brackets {...} you can then use i as a key to access the arrays values

Now this is all very powerful and nice, but it gets cumbersome to write every time, especially if in most of the cases you just want to iterate over an array. But luckily we have for-in:

For-in will retrieve you all the keys you have set yourself. With an array, you can use that to achieve the same result as above using

for(let i in array) {...}

Note however, that for-in is not only gonna give you the number keys from an array. It is also gonna work on other keys you have set yourself on any object:

let object = {
    key1 : 'value',
    key2 : 'value'
}

for(let i in object) {
    console.log(i)
}

will log out 'key1' and 'key2' (yes, the keys as well are strings here).

For a bit more precise description of what keys exactly it will give you, have a look at the link below.

When would you use for-in? Whenever you want to call some code for each element of an array / (almost) each property of an object once. E.g. when you want to increment all values in an array by 1. When not to use for-in? Don't use it if you need more granular control over the order you traverse the array in, or you don't want to hit all elements of the array, but only every second/third.

For an excellent resource on for-in loops I recommend Mozilla Developer Network

So, what are for-of loops then?

For-of loops are syntactically (i.e. the way you write them) very similar to for-in loops:

for(let v of array) {...}

However, for one, they are only going to work on so-called iterable objects (arrays are iterable). Second, you only get the values. They are no longer going to give you any keys!

let array = ['a', 'b', 'c']
for(let v of array) {
    console.log(v)
}

logs 'a', 'b' and 'c'. You won't know anymore, what keys these values had!

So, when to use these? Every time you just need the values and don't care about the keys. E.g. if you just want to print the values. When not to use them? If you want to swap elements of an array, if you want to reverse order. You can't even increment the values by 1 and store them back into the array, because for that, you would need to know their corresponding key.

For more information on for-in loops as well as what iterable actually means, again, I recommend the MDN

2 of 2
2

The only key differences that you'll have to consider would be

  • Say you want to start your loop from a specific index, you can do that with your traditional for loop but not using for...of.

  • You can't access indices of your array elements natively. You'll need to go for a workaround to achieve this.

      //Cannot access indices
      for(const num of [11,22,33,44,55]){
         console.log(num);
      }
    
    
      //Workaround
      for(const [index, num] of [11,22,33,44,55].entries()){
         console.log(num, index);
      }
    
🌐
freeCodeCamp
freecodecamp.org › news › javascript-for-loops
JavaScript For Loop – Explained with Examples
November 7, 2024 - We're only going to look at JavaScript ... The for loop is an iterative statement which you use to check for certain conditions and then repeatedly execute a block of code as long as those conditions are met....
Top answer
1 of 16
5292

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.