Non-iterable values should not be iterated

  • ITERATE_NON_ITERABLE
  • Error
  • High
  • es6

This rule applies when a non-iterable value is used at syntaxes requiring iterables. In such a case, a TypeError exception is thrown.

Iterable values are required at the following syntaxes:

  1. for-of loop
  2. for-await-of loop (async iterable objects can also be used)
  3. yield* (inside async generator functions, async iterable objects can also be used)
  4. Array pattern
  5. Array spread
  6. Argument spread

In JavaScript, the following values are iterable:

  1. Array, TypedArray
  2. Map, WeakMap
  3. Set, WeakSet
  4. String (each character in the string is iterated)
  5. Generator objects returned by generator functions
  6. Any objects implementing the Symbol.iterator property

Noncompliant Code Example

View with compliant examples side by side
function example1(x, a, b) {
    let others = {a, b};
    return [x, ...others]; // ITERATE_NON_ITERABLE alarm because 'others' is a plain object.
}

async function example2() {
    async function* generate(n) {
        for (let i = 0; i < n; i++) {
            let x = await getSomething(i);
            yield x;
        }
    }
    for (let x of generate(10)) { // ITERATE_NON_ITERABLE alarm because async generator functions return async iterable objects.
        doSomething(await x);
    }
}

Compliant Code Example

View with noncompliant examples side by side
function example1(x, a, b) {
    let others = [a, b];
    return [x, ...others];
}

async function example2() {
    async function* generate(n) {
        for (let i = 0; i < n; i++) {
            let x = await getSomething(i);
            yield x;
        }
    }
    for await (let x of generate(10)) {
        doSomething(x);
    }
}

Version

This rule was introduced in DeepScan 1.38.0.

See

Was this documentation helpful?