JavaScript for Loop with Index Examples

Learn how to get the index in JavaScript for loops with for...of, entries(), for...in, and practical index output examples.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

JavaScript for Loop with Index Examples

Getting the index in a JavaScript loop is useful when you need both the item and its position in an array. The best method depends on whether you want the key, the value, or both.

for...of with entries() is usually the cleanest choice for arrays. If you compare loop styles often, JavaScript forEach vs for...in is the related topic.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Use for...in to get the index

for...in iterates over property names, which gives you the array index for plain arrays.

javascript
const xdg = [23, 45, 6];

for (let index in xdg) {
  console.log("for-in-index:", index);
}
Output

You should see 3 lines, in order: for-in-index: 0, for-in-index: 1, for-in-index: 2.

Use this carefully because for...in also walks inherited enumerable properties.


Method 2: Use for...of with entries()

entries() returns [index, value] pairs that are easy to destructure.

javascript
const clubs = ["manchester united", "chelsea", "arsenal"];

for (const [index, club] of clubs.entries()) {
  console.log("for-index:", index, club);
}
Output

You should see 3 lines, in order: for-index: 0 manchester united, for-index: 1 chelsea, for-index: 2 arsenal.

This is the most readable way to get the index and value together in modern JavaScript.


Method 3: Use forEach when you only need array position

forEach() passes the current value, index, and array to the callback.

javascript
const clubs = ["manchester united", "chelsea", "arsenal"];

clubs.forEach((club, index) => {
  console.log("for-each-index:", index, club);
});
Output

You should see 3 lines, in order: for-each-index: 0 manchester united, for-each-index: 1 chelsea, for-each-index: 2 arsenal.

This is a practical option when you want a simple indexed loop without manual counters.


Summary

To get the index in a JavaScript loop, use for...in when you need property names, for...of with entries() when you want both index and value, and forEach() when a callback-based loop is enough. For arrays, entries() is usually the cleanest choice.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …