How do you access both index and value when looping with for...of in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you access both index and value when looping with for...of in JavaScript?

message-square
0

To access both the index and the value when looping with for...of in JavaScript, call array.entries() on the array and destructure each yielded [index, value] pair (for (const [index, value] of items.entries())). Unlike for...in (which iterates enumerable property keys across objects and prototypes rather than guaranteed ordered numeric array indices), for...of with .entries() cleanly yields exact zero-based numeric indices and values in order without mutating the array.


1. Using for...of with Array.prototype.entries() and Destructuring

Call items.entries() to get an iterator of [index, element] pairs, then use for (const [index, value] of items.entries()) to access both cleanly:

// Non-mutating helper returning formatted "index: value" entries via for...of + entries()
function formatIndexedItems(items) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an array.");
  }

  const formatted = [];

  for (const [index, value] of items.entries()) {
    formatted.push(`${index}: ${String(value)}`);
  }

  return formatted;
}

// Example usage:
const tasks = ["Lint code", "Run tests", "Deploy build"];
console.log(formatIndexedItems(tasks));
// ["0: Lint code", "1: Run tests", "2: Deploy build"]
console.log(tasks); // ["Lint code", "Run tests", "Deploy build"] (unchanged)
  • const per iteration: Using for (const [index, value] ...) creates fresh bindings on each iteration and avoids accidental reassignment bugs.
  • Works with break, continue, and return: Unlike .forEach(), for...of lets you exit early or skip iterations naturally.

2. Why for...in Is Not Recommended for Arrays

A common mistake is using for (const index in items) on arrays; for...in iterates over string keys of all enumerable properties (including custom properties added to an array or inherited enumerable properties), whereas for...of with .entries() iterates true sequential array indices:

// Find the first index matching a predicate using early exit inside for...of + entries()
function findFirstMatchingIndex(items, predicate) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an array.");
  }

  if (typeof predicate !== "function") {
    throw new TypeError("Expected predicate to be a function.");
  }

  for (const [index, value] of items.entries()) {
    if (predicate(value, index, items)) {
      return index;
    }
  }

  return -1;
}

// Example usage:
const scores = [42, 88, 95, 71];
console.log(findFirstMatchingIndex(scores, (score) => score >= 80)); // 1
  • index from .entries() is a number: for...in yields property keys as strings ("0", "1"), whereas [index, value] from .entries() provides numeric indices (0, 1).
  • Respects array order and length: .entries() steps from 0 up to items.length - 1 in order.

3. Iterating Other Iterables, Maps, and Sets with for...of

Plain for...of works on any iterable (strings, Set, Map, NodeList, generators), while Map.prototype.entries() yields [key, value] pairs and Array.from(iterable).entries() lets you index other iterables when needed:

// Pair elements from two arrays by index without mutating either array
function zipArraysByIndex(leftItems, rightItems) {
  if (!Array.isArray(leftItems) || !Array.isArray(rightItems)) {
    throw new TypeError("Expected both leftItems and rightItems to be arrays.");
  }

  const limit = Math.min(leftItems.length, rightItems.length);
  const paired = [];

  for (const [index, leftValue] of leftItems.entries()) {
    if (index >= limit) {
      break;
    }
    paired.push({ index, left: leftValue, right: rightItems[index] });
  }

  return paired;
}

// Example usage:
console.log(zipArraysByIndex(["a", "b", "c"], [10, 20]));
// [{ index: 0, left: "a", right: 10 }, { index: 1, left: "b", right: 20 }]
  • Check .length bounds when indexing a second array: Guarding with index < rightItems.length prevents reading undefined past the shorter array’s end.
  • Use for...of + .entries() for async/early-exit loops: When you need await inside the loop or early break/return, for...of + .entries() is much cleaner than .forEach().

TL;DR: Use for (const [index, value] of array.entries()) to get both the zero-based index and value in a for...of loop while preserving early exit (break/return) and avoiding for...in key quirks.