A for...of
loop operates on the values sourced from an iterable one by one in sequential order. Each operation of the loop on a value is called an iteration, and the loop is said to iterate over the iterable. Each iteration executes statements that may refer to the current sequence value.
When a for...of
loop iterates over an iterable, it first calls the iterable's [@@iterator]()
method, which returns an iterator, and then repeatedly calls the resulting iterator's next()
method to produce the sequence of values to be assigned to variable
.
A for...of
loop exits when the iterator has completed (the iterator's next()
method returns an object containing done: true
). You may also use control flow statements to change the normal control flow. break
exits the loop and goes to the first statement after the loop body, while continue
skips the rest of the statements of the current iteration and proceeds to the next iteration.
If the for...of
loop exited early (e.g. a break
statement is encountered or an error is thrown), the return()
method of the iterator is called to perform any cleanup.
The variable
part of for...of
accepts anything that can come before the =
operator. You can use const
to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables). Otherwise, you can use let
.
const iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
Note: Each iteration creates a new variable. Reassigning the variable inside the loop body does not affect the original value in the iterable (an array, in this case).
You can use destructuring to assign multiple local variables, or use a property accessor like for (x.y of iterable)
to assign the value to an object property.
However, a special rule forbids using async
as the variable name. This is invalid syntax:
let async;
for (async of [1, 2, 3]);
This is to avoid syntax ambiguity with the valid code for (async of => {};;)
, which is a for
loop.