javascript
index
loop
for

How to access the index value in a 'for' loop?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In JavaScript, the "right" way to access an index depends on which looping style you are using. Arrays support several iteration patterns, and some expose the index directly while others require a helper such as entries() or a callback parameter.

The Standard for Loop

The classic for loop gives you direct control of the index variable, which makes it the most explicit choice.

javascript
1const items = ["a", "b", "c"];
2
3for (let i = 0; i < items.length; i++) {
4  console.log(`index=${i}, value=${items[i]}`);
5}

This is still a good option when:

  • you need the index often
  • you may skip or jump iterations
  • you want to iterate backward

For example:

javascript
for (let i = items.length - 1; i >= 0; i--) {
  console.log(items[i]);
}

That kind of control is harder to express cleanly with higher-level iteration helpers.

Using forEach

If you want readable array iteration and do not need to break early, forEach exposes the index as the second callback argument:

javascript
1const items = ["a", "b", "c"];
2
3items.forEach((value, index) => {
4  console.log(`index=${index}, value=${value}`);
5});

This is concise and easy to read, but it has limits:

  • you cannot use break
  • 'return only exits the callback, not the outer function'
  • async callbacks do not behave like sequential await loops

So forEach is convenient, but it is not a universal replacement for for.

Using for...of with entries()

for...of normally gives you values, not indexes. To get both, iterate over array.entries().

javascript
1const items = ["a", "b", "c"];
2
3for (const [index, value] of items.entries()) {
4  console.log(`index=${index}, value=${value}`);
5}

This is often the cleanest modern pattern when you want:

  • the readability of for...of
  • direct access to both index and value
  • support for break, continue, and await

For many codebases, this is the best balance between clarity and flexibility.

Avoid for...in for Arrays

JavaScript also has for...in, but it is meant for object property keys, not normal array iteration.

javascript
1const items = ["a", "b", "c"];
2
3for (const key in items) {
4  console.log(`key=${key}, value=${items[key]}`);
5}

This may appear to work, but it has drawbacks:

  • the index comes through as a string
  • inherited enumerable properties may appear
  • it communicates the wrong intent to readers

Use for...in for objects, not arrays, unless you have a very specific reason.

Index Access with Async Code

One place where loop choice matters is asynchronous work. forEach is a common trap here because it does not wait for await the way many people expect.

Problematic pattern:

javascript
1const items = ["a", "b", "c"];
2
3items.forEach(async (value, index) => {
4  await new Promise(resolve => setTimeout(resolve, 100));
5  console.log(index, value);
6});

If you need sequential async behavior with indexes, prefer:

javascript
1const items = ["a", "b", "c"];
2
3for (const [index, value] of items.entries()) {
4  await new Promise(resolve => setTimeout(resolve, 100));
5  console.log(index, value);
6}

That is one reason entries() is so useful in modern JavaScript.

Choosing the Best Pattern

A practical rule is:

  • use classic for when you want maximum control
  • use forEach for simple synchronous callbacks
  • use for...of with entries() for readable value-plus-index iteration

There is no single mandatory style, but the loop should match the job. If index arithmetic matters, the classic for loop often remains the clearest answer.

Common Pitfalls

The most common mistake is using for...in on arrays. It works differently from normal indexed iteration and can produce confusing results.

Another issue is forgetting that forEach does not support break or continue. If you need early exit, pick a different loop.

Developers also trip over async code inside forEach. The callback can start multiple asynchronous operations without waiting for them in sequence.

Finally, avoid overcomplicating simple loops. If you only need the index and value once, for...of with entries() is often simpler than manual counter management.

Summary

  • The classic for loop gives you direct access to the index variable.
  • 'forEach exposes the index as the second callback argument.'
  • 'for...of plus entries() is a clean modern way to get both index and value.'
  • 'for...in is usually the wrong tool for arrays.'
  • For async iteration with indexes, prefer for...of with entries() over forEach.

Course illustration
Course illustration

All Rights Reserved.