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
492

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.

🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Loops_and_iteration
Loops and iteration - JavaScript | MDN
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 - 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). Knowing the position, or index, can be really helpful for things like: Updating items in a list based on their position. Keeping track of items with numbers to link them to other info.
🌐
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.
🌐
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 - To add an index to the for...of loop, you can use the entries() method of an array, which returns an iterable containing index-value pairs.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › for...in
for...in - JavaScript | MDN
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
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'
🌐
Esdiscuss
esdiscuss.org › topic › for-statement-with-index-and-value
for statement with index and value
But I'm pretty sure you also need the current index of array in a for loop. Since I can access the index and value directly in `.forEach(value, index, array)`, why isn't there a for-loop-statement/control-flow-statement for doing the same thing? And yes I heard it can be solved with different methods.
Find elsewhere
🌐
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.
🌐
GoLinuxCloud
golinuxcloud.com › home › javascript › get index in for loop of javascript [solved]
Get index in for loop of JavaScript [Solved] | GoLinuxCloud
November 11, 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 ...
🌐
Devpractical
devpractical.com › javascript-for-loop-with-index
How to Use Javascript for Loop with Index [4 Examples] · DevPractical
The for loop is a powerful control structure that allows you to repeat a block of code a specified number of times. The index is a variable that keeps track of the current iteration of the loop. This variable is updated with each iteration of the loop, allowing you to access the current index ...
🌐
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
Answer (1 of 2): Hi there, I am currently learning how to code but I don’t quite understand how to solve this task. Please can someone explain where I am going wrong? Task: Write a for loop which finds the index position of the duckling and assigns it to the provided variable [code ]'ducklingHe...
🌐
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 ...
🌐
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.

🌐
Exploring JS
exploringjs.com › es6 › ch_for-of.html
17. The for-of loop
Access both elements and their indices while looping over an Array (the square brackets before of mean that we are using destructuring): const arr = ['a', 'b']; for (const [index, element] of arr.entries()) { console.log(`${index}. ${element}`); } // Output: // 0.
🌐
The Valley of Code
thevalleyofcode.com › lesson › js-recipes › loop-with-index
JavaScript Recipes: Get Index in for...of Loop
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:
🌐
Go Make Things
gomakethings.com › getting-the-index-in-a-for...of-loop
Getting the index in a for...of loop | Go Make Things
wizards.forEach((wizard, index) => { console.log(wizard, index); }); It works, it’s fine, whatever. But there are some important differences. You can’t continue in a .forEach() callback. You return to end the current callback function and jump to the next one. And you can’t break to end the loop early.