Skip to main content

Iterators and generators

Prefer functional iteration patterns over imperative loops, and avoid generators until they transpile reliably.

11.1 Don’t use iterators

eslint: no-iterator, no-restricted-syntax Prefer JavaScript’s higher-order functions instead of loops like for-in or for-of. This enforces immutability. Dealing with pure functions that return values is easier to reason about than side effects. Use map() / every() / filter() / find() / findIndex() / reduce() / some() to iterate over arrays, and Object.keys() / Object.values() / Object.entries() to produce arrays so you can iterate over objects.
const numbers = [1, 2, 3, 4, 5];

// good
let sum = 0;
numbers.forEach((num) => {
  sum += num;
});
sum === 15;

// best (use the functional force)
const sum = numbers.reduce((total, num) => total + num, 0);
sum === 15;

// good
const increasedByOne = [];
numbers.forEach((num) => {
  increasedByOne.push(num + 1);
});

// best (keeping it functional)
const increasedByOne = numbers.map((num) => num + 1);
Higher-order functions like reduce, map, and filter make intent explicit and avoid accidental mutation of external state.

11.2 Don’t use generators for now

Generators don’t transpile well to ES5.
If your target environment natively supports generators, or you are not transpiling to ES5, this restriction may not apply. See rule 11.3 for proper formatting if you must use them.

11.3 Space generator function signatures properly

eslint: generator-star-spacing If you must use generators, make sure their function signature is spaced properly. function and * are part of the same conceptual keyword — * is not a modifier for function. function* is a unique construct, different from function.
function* foo() {
  // ...
}

const foo = function* () {
  // ...
};

Properties

Use dot notation by default, bracket notation for dynamic access, and ** for exponentiation.

12.1 Use dot notation when accessing properties

eslint: dot-notation
const luke = {
  jedi: true,
  age: 28,
};

const isJedi = luke.jedi;

12.2 Use bracket notation for variable property access

Use bracket notation [] when accessing properties with a variable.
const luke = {
  jedi: true,
  age: 28,
};

function getProp(prop) {
  return luke[prop];
}

const isJedi = getProp('jedi');
Bracket notation is necessary when the property name is dynamic — stored in a variable or computed at runtime.

12.3 Use the exponentiation operator **

eslint: prefer-exponentiation-operator Use the exponentiation operator ** when calculating exponentiations instead of Math.pow.
const binary = 2 ** 10;

Build docs developers (and LLMs) love