Section

Operators & Control Flow

Priority

Low

Difficulty

Easy

Duration

5 min

How do you access the index of an element in an array during iteration?

To access the index of an element in an array during iteration, you can use methods like `forEach`, `map`, `for...of` with `entries`, or a traditional `for` loop. For example, using `forEach`:

Javascript

TL;DR

To access the index of an element in an array during iteration, you can use methods like forEach, map, for...of with entries, or a traditional for loop. For example, using forEach:

const array = ['a', 'b', 'c'];
array.forEach((element, index) => {
  console.log(index, element);
});

Using forEach

The forEach method executes a provided function once for each array element. The callback function takes three arguments: the current element, the index of the current element, and the array itself.

const array = ['a', 'b', 'c'];
array.forEach((element, index) => {
  console.log(index, element);
});

Using map

The map method creates a new array populated with the results of calling a provided function on every element in the calling array. The callback function also takes three arguments: the current element, the index of the current element, and the array itself.

const array = ['a', 'b', 'c'];
array.map((element, index) => {
  console.log(index, element);
});

Using for...of with entries

The for...of loop can be combined with the entries method to access both the index and the element.

const array = ['a', 'b', 'c'];
for (const [index, element] of array.entries()) {
  console.log(index, element);
}

Using a traditional for loop

A traditional for loop gives you direct access to the index.

const array = ['a', 'b', 'c'];
for (let index = 0; index < array.length; index++) {
  console.log(index, array[index]);
}

Further reading