Skip to content

JavaScript for of index

  • by

The for...of loop in JavaScript is used to iterate over the values of an iterable object. While it does not provide an index directly, you can use the Array.prototype.entries() method to access both the index and the value of each element.

for (const [index, value] of iterable.entries()) {
  // code to be executed for each iteration
}
  • for...of: The keyword that starts the loop.
  • const [index, value]: Destructuring assignment syntax that extracts the index and value from each element of the iterable object. You can use any variable names you prefer.
  • of: The keyword that separates the variable assignment from the iterable object.
  • iterable: The iterable object you want to iterate over, such as an array or a string.
  • .entries(): The method called on the iterable object to obtain an iterator that provides both the index and value for each element.

Note: If you’re working with older JavaScript versions, you can resort to a traditional for loop to achieve the same result.

for (let index = 0; index < iterable.length; index++) {
  const value = iterable[index];
  // code to be executed for each iteration
}

JavaScript for-of index example

Simple example code.

const array = ['apple', 'banana', 'cherry'];

for (const [index, value] of array.entries()) {
  console.log(`Index: ${index}, Value: ${value}`);
}

Output:

index variable

The entries() method is not supported in older versions of JavaScript (pre-ES2015). In such cases, you can use a traditional for loop with the index variable to achieve the same result:

const arr = ['a', 'b', 'c'];

for (let index = 0; index < arr.length; index++) {
  const value = arr[index];
  console.log(index, value);
}

Comment if you have any doubts or suggestions on this Js loop topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading