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(`{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_{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.

Answer from Ry- on Stack Overflow
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(`{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_{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.

🌐
Medium
medium.com › @_DandyLyons › how-to-use-a-js-for-of-loop-with-an-index-a4675ed22351
How to use a JS for…of loop with an index | Medium
April 19, 2024 - By leveraging the entries() method, you can easily include an index alongside the values in your loops. This can be especially useful when you need to perform operations that require knowledge of the element's position within the iterable.
Discussions

javascript - Access to ES6 array element index inside for-of loop - Stack Overflow
See similar questions with these tags. ... I’m Jody, the Chief Product and Technology Officer at Stack Overflow. Let’s... Release notes and bug fixes for beta.stackoverflow.com ... 0 What is the simple way to get value and index on For of loop out of an array in Javascript / ReactNative? More on stackoverflow.com
🌐 stackoverflow.com
How to loop through an array & exiting after a certain index [JavaScript]
You're incrementing i and not k. In you for loop statement, you wrote for(k=0; k< people.lenght; i++){} . Instead of i, just put k and you should be able to print all of the strings in the array. To stop whenever Mary is read, just do a simple if(people[k] === 'Mary'){ break; or return;} It depends if you're in a function or not More on reddit.com
🌐 r/learnprogramming
14
5
May 7, 2023
why going back to the index when using 'for loop' is bad practice?
It's a sign you maybe used the wrong kind of loop. We have for, foreach and the various forms of while. Let's ignore foreach and talk about the semantics of for and while with respect to each other. for is when we want to use some variable that changes with a very predictable pattern on each iteration. while is when we expect the terminating condition to be complex, and we might not be predictably altering state with each loop. That's why it's "bad practice" to change your for index variable. People reading code don't expect to see you do that. Even very smart people are prone to missing the "obvious" line because when people see for they turn their brain off. You can help them keep their brain on by using a while loop instead. It is slightly more complicated to write, which means you will pay more attention to it when it's read. We tend to write code once and read it hundreds of times, so it's best to optimize for the reader. More on reddit.com
🌐 r/csharp
24
18
August 27, 2019
Javascript: For In loop does not loop through array in order past certain index
What do you think the "safe number" limit is? JavaScript array indexes are limited to 4294967294, and so 9999999999 is larger than that. JavaScript is pretty quirky. When you use indexes larger than that, it doesn't break, but it starts behaving more like an associative array. More on reddit.com
🌐 r/learnprogramming
15
3
August 29, 2022
🌐
Esdiscuss
esdiscuss.org › topic › for-statement-with-index-and-value
for statement with index and value
The following will result in the wrong index for the last item: ... Also that construct is not very performant. ... That only works if all values are distinct. The following will result in the wrong index for the last item: let values = ["a", "b", "a"]; for (let value of values) { let index = values.indexOf(value); } Also that construct is not very performant.
🌐
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).
🌐
daily.dev
daily.dev › home › blog › get into tech › understanding javascript for of with index
Understanding Javascript for of with index
December 22, 2025 - Getting good at using indexes can help you sort arrays, link values with their positions, keep things in order, and more. It's a key part of making your JavaScript code work well. So, practice using for...of loops with entries() and keys() until you're comfortable.
🌐
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 ...
🌐
Futurestud.io
futurestud.io › tutorials › how-to-get-an-index-in-a-for-of-loop-in-javascript-and-node-js
How to Get an Index in a for…of Loop in JavaScript and Node.js
May 6, 2021 - Use JavaScript’s Array#entries method to create an array iterator. This iterator returns a key-value-pair for each index-value combination in the array. You can then destructure the index-value-pair using the array notation: for (const [index, value] of ['Future', 'Studio'].entries()) { console.log(index, value) } // 0 'Future' // 1 'Studio'
Find elsewhere
🌐
GoLinuxCloud
golinuxcloud.com › home › javascript › get index in for loop of javascript [solved]
Get index in for loop of JavaScript [Solved] | GoLinuxCloud
November 12, 2022 - for..of allows us to access the element of the array directly without having to use any index value which is typically inserted into the array square notation (arr[index). In this article, we will discuss how to get index in for...of JavaScript ...
🌐
W3Schools
w3schools.com › js › js_loop_forin.asp
JavaScript For In
Properties with the enumerable attribute is set to false, like some built-in methods or properties defined with Object.defineProperty() will not be included. The for...in loop also iterates over enumerable properties inherited from the object's prototype chain. To avoid this, you can use hasOwnProperty() inside the loop to check if the property belongs directly to the object itself. Do not use for in over an Array if the index order is important.
🌐
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 - We need to define a counter initialized to zero, then increment the counter by one until it reaches the size of the array. Then, for each iteration, we have to extract the value from the array when the index matches the current value of our counter.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › array › array index in for...of loops
Get the index of an array item in a JavaScript for...of loop - 30 seconds of code
July 25, 2021 - const items = ['a', 'b', 'c']; for (let [index, item] of items.entries()) { console.log(`${index}: ${item}`); } // LOGS: 0: a, 1: b, 2: c · Moreover, you can use the spread operator (...) to convert a string into an array and then use Array.prototype.entries() the same way. Finally, both Map and Set prototypes provide a similar method (Map.prototype.entries() and Set.prototype.entries() respectively), which can be used the exact same way. If you're not familiar with for...of and its syntax, I highly recommending you take a look at this article about the various iteration methods in JavaScript.
🌐
Quora
quora.com › How-do-I-write-a-for-loop-which-finds-the-index-position-and-then-assigns-it-to-the-provided-variable-JavaScript-1
How to write a for loop which finds the index position and then assigns it to the provided variable (JavaScript) - Quora
... There are several ways of doing this. Here’s a simple one: First we split the string into an array of words. Then, we can use for …of to loop over the data. ... MDN: split method (https://docs.microsoft.com/en-us/scripting/javascrip...
🌐
Log4JavaScript
log4javascript.org › home › js-framework › demystifying the javascript for loop index
Exploring the JavaScript for Loop Index: A Complete Guide
July 4, 2023 - In this example, i represents the index of each element in the numbers array, allowing you to access and work with each element individually within the loop. Iterations provide a convenient and efficient method for performing repetitive tasks. This section of the JavaScript Guide introduces ...
🌐
Exploring JS
exploringjs.com › es6 › ch_for-of.html
17. The for-of loop
const arr = ['a', 'b']; for (const [index, element] of arr.entries()) { console.log(`${index}. ${element}`); } // Output: // 0. a // 1. b · Looping over the [key, value] entries in a Map (the square brackets before of mean that we are using destructuring):
🌐
The Valley of Code
thevalleyofcode.com › lesson › js-recipes › loop-with-index
Get Index in for...of Loop - JavaScript Recipes
for (const v of ['a', 'b', 'c']) { console.log(v) } ... The loop does not offer any syntax to do this, but you can combine the destructuring syntax introduced in ES6 with calling the entries() method on the array:
🌐
Reddit
reddit.com › r/learnprogramming › how to loop through an array & exiting after a certain index [javascript]
r/learnprogramming on Reddit: How to loop through an array & exiting after a certain index [JavaScript]
May 7, 2023 -

As the title states, I was given this prompt

Using a loop, iterate through this array and after console.logging “Mary”, exit from the loop.

The array is

let people = ['Matt', 'Mary', 'Devon', 'Anthony']

I tried this for loop & technically I was able to get the result, but I'm pretty sure it's not the right way.

for (k = 0; k < 4; i++){
   if (people.splice(2,4)) {
        console.log(people);
        break;
    } else {
        console.log(people[k]);
    }
}

Could someone please correct me if I'm wrong.

I tried setting the conditional to

k < 1

That way it counts from the 0 index, to the first, which is where Mary is & then

exit

From the loop by using

break;

But that didn't work with my if statement of

if (people) {}

That's why I just decided to use the splice method to kind of brute force the result per se.

This is what my original code looked like

for (k = 0; k < 1; i++){
   if (people) {
        console.log(people[k]);
        break;
    } else {
        console.log(people[k]);
    }
}

But this way only prints Matt at the beginning of the array.

🌐
Go Make Things
gomakethings.com › getting-the-index-in-a-for...of-loop
Getting the index in a for...of loop | Go Make Things
July 14, 2025 - You can then destructure the array to access the index in the loop. for (const [index, wizard] of wizards.entries()) { console.log(wizard, index); } Here’s a demo on CodePen. Was this helpful? A Go Make Things Membership is the best way to support my work, and helps keep my content free and open to everyone. Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a better web and more. Join over 8.9k others. Or subscribe with RSS...
🌐
SitePoint
sitepoint.com › blog › javascript › how to use the for loop in javascript
For Loop in JavaScript: How to Use the for…in Loop — SitePoint
November 7, 2024 - There are two ways to access an item in a collection. The first way is via its key in the collection, which is an index in an array or a property in an object. The second way is via the item itself, without needing the key.