Path: blob/main/files/en-us/web/javascript/reference/statements/for...of/index.md
6524 views
------{{jsSidebar("Statements")}}
The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as {{jsxref("Array")}}, {{jsxref("String")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{domxref("NodeList")}} (and other DOM collections), as well as the {{jsxref("Functions/arguments", "arguments")}} object, generators produced by generator functions, and user-defined iterables.
{{EmbedInteractiveExample("pages/js/statement-forof.html")}}
Syntax
variable: Receives a value from the sequence on each iteration. May be either a declaration with
const,let, orvar, or an assignment target (e.g. a previously declared variable or an object property).
iterable: An iterable object. The source of the sequence of values on which the loop operates.
statement: A statement to be executed on every iteration. May reference
variable. You can use a block statement to execute multiple statements.
Description
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 {{jsxref("Statements/const", "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 {{jsxref("Statements/let", "let")}}.
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 or an object property like for (x.y of iterable) as well.
However, a special rule forbids using async as the variable name. This is invalid syntax:
This is to avoid syntax ambiguity with the valid code for (async of => {};;), which is a for loop.
Examples
Iterating over an Array
Iterating over a string
Strings are iterated by Unicode code points.
Iterating over a TypedArray
Iterating over a Map
Iterating over a Set
Iterating over the arguments object
You can iterate over the {{jsxref("Functions/arguments", "arguments")}} object to examine all parameters passed into a function.
Iterating over a NodeList
The following example adds a read class to paragraphs that are direct descendants of the <article> element by iterating over a NodeList DOM collection.
Iterating over a user-defined iterable
Iterating over an object with an @@iterator method that returns a custom iterator:
Iterating over an object with an @@iterator generator method:
Iterable iterators (iterators with a [@@iterator]() method that returns this) are a fairly common technique to make iterators usable in syntaxes expecting iterables, such as for...of.
Iterating over a generator
Early exiting
Execution of the break statement in the first loop causes it to exit early. The iterator is not finished yet, so the second loop will continue from where the first one stopped at.
Generators implement the return() method, which causes the generator function to early return when the loop exits. This makes generators not reusable between loops.
Difference between for...of and for...in
Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over.
The {{jsxref("Statements/for...in", "for...in")}} statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.
The following example shows the difference between a for...of loop and a for...in loop when used with an {{jsxref("Array")}}.
The object iterable inherits the properties objCustom and arrCustom because it contains both Object.prototype and Array.prototype in its prototype chain.
The for...in loop logs only enumerable properties of the iterable object. It doesn't log array elements 3, 5, 7 or "hello" because those are not properties — they are values. It logs array indexes as well as arrCustom and objCustom, which are actual properties. If you're not sure why these properties are iterated over, there's a more thorough explanation of how array iteration and for...in work.
The second loop is similar to the first one, but it uses {{jsxref("Object.hasOwn()")}} to check if the found enumerable property is the object's own, i.e. not inherited. If it is, the property is logged. Properties 0, 1, 2 and foo are logged because they are own properties. Properties arrCustom and objCustom are not logged because they are inherited.
The for...of loop iterates and logs values that iterable, as an array (which is iterable), defines to be iterated over. The object's elements 3, 5, 7 are shown, but none of the object's properties are.
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
{{jsxref("Array.prototype.forEach()")}}
{{jsxref("Map.prototype.forEach()")}}
{{jsxref("Object.entries()")}} – Useful when using
for...ofover an object.