Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

for...of

BaselineWidely available

Thefor...of statement executes a loop that operates on a sequence of values sourced from aniterable object. Iterable objects include instances of built-ins such asArray,String,TypedArray,Map,Set,NodeList (and other DOM collections), as well as thearguments object,generators produced bygenerator functions, and user-defined iterables.

Try it

const array1 = ["a", "b", "c"];for (const element of array1) {  console.log(element);}// Expected output: "a"// Expected output: "b"// Expected output: "c"

Syntax

js
for (variable of iterable)  statement
variable

Receives a value from the sequence on each iteration. May be either a declaration withconst,let, orvar, or anassignment target (e.g., a previously declared variable, an object property, or adestructuring pattern). Variables declared withvar are not local to the loop, i.e., they are in the same scope thefor...of loop is in.

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 referencevariable. You can use ablock statement to execute multiple statements.

Description

Afor...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 aniteration, and the loop is said toiterate over the iterable. Each iteration executes statements that may refer to the current sequence value.

When afor...of loop iterates over an iterable, it first calls the iterable's[Symbol.iterator]() method, which returns aniterator, and then repeatedly calls the resulting iterator'snext() method to produce the sequence of values to be assigned tovariable.

Afor...of loop exits when the iterator has completed (thenext() result is an object withdone: true). Like other looping statements, you can usecontrol flow statements insidestatement:

  • break stopsstatement execution and goes to the first statement after the loop.
  • continue stopsstatement execution and goes to the next iteration of the loop.

If thefor...of loop exited early (e.g., abreak statement is encountered or an error is thrown), thereturn() method of the iterator is called to perform any cleanup.

Thevariable part offor...of accepts anything that can come before the= operator. You can useconst 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 uselet.

js
const iterable = [10, 20, 30];for (let value of iterable) {  value += 1;  console.log(value);}// 11// 21// 31

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 usedestructuring to assign multiple local variables, or use a property accessor likefor (x.y of iterable) to assign the value to an object property.

However, a special rule forbids usingasync as the variable name. This is invalid syntax:

js
let async;for (async of [1, 2, 3]); // SyntaxError: The left-hand side of a for-of loop may not be 'async'.

This is to avoid syntax ambiguity with the valid codefor (async of => {};;), which is afor loop.

Examples

Iterating over an Array

js
const iterable = [10, 20, 30];for (const value of iterable) {  console.log(value);}// 10// 20// 30

Iterating over a string

Strings areiterated by Unicode code points.

js
const iterable = "boo";for (const value of iterable) {  console.log(value);}// "b"// "o"// "o"

Iterating over a TypedArray

js
const iterable = new Uint8Array([0x00, 0xff]);for (const value of iterable) {  console.log(value);}// 0// 255

Iterating over a Map

js
const iterable = new Map([  ["a", 1],  ["b", 2],  ["c", 3],]);for (const entry of iterable) {  console.log(entry);}// ['a', 1]// ['b', 2]// ['c', 3]for (const [key, value] of iterable) {  console.log(value);}// 1// 2// 3

Iterating over a Set

js
const iterable = new Set([1, 1, 2, 2, 3, 3]);for (const value of iterable) {  console.log(value);}// 1// 2// 3

Iterating over the arguments object

You can iterate over thearguments object to examine all parameters passed into a function.

js
function foo() {  for (const value of arguments) {    console.log(value);  }}foo(1, 2, 3);// 1// 2// 3

Iterating over a NodeList

The following example adds aread class to paragraphs that are direct descendants of the<article> element by iterating over aNodeList DOM collection.

js
const articleParagraphs = document.querySelectorAll("article > p");for (const paragraph of articleParagraphs) {  paragraph.classList.add("read");}

Iterating over a user-defined iterable

Iterating over an object with an[Symbol.iterator]() method that returns a custom iterator:

js
const iterable = {  [Symbol.iterator]() {    let i = 1;    return {      next() {        if (i <= 3) {          return { value: i++, done: false };        }        return { value: undefined, done: true };      },    };  },};for (const value of iterable) {  console.log(value);}// 1// 2// 3

Iterating over an object with an[Symbol.iterator]() generator method:

js
const iterable = {  *[Symbol.iterator]() {    yield 1;    yield 2;    yield 3;  },};for (const value of iterable) {  console.log(value);}// 1// 2// 3

Iterable iterators (iterators with a[Symbol.iterator]() method that returnsthis) are a fairly common technique to make iterators usable in syntaxes expecting iterables, such asfor...of.

js
let i = 1;const iterator = {  next() {    if (i <= 3) {      return { value: i++, done: false };    }    return { value: undefined, done: true };  },  [Symbol.iterator]() {    return this;  },};for (const value of iterator) {  console.log(value);}// 1// 2// 3

Iterating over a generator

js
function* source() {  yield 1;  yield 2;  yield 3;}const generator = source();for (const value of generator) {  console.log(value);}// 1// 2// 3

Early exiting

Execution of thebreak 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.

js
const source = [1, 2, 3];const iterator = source[Symbol.iterator]();for (const value of iterator) {  console.log(value);  if (value === 1) {    break;  }  console.log("This string will not be logged.");}// 1// Another loop using the same iterator// picks up where the last loop left off.for (const value of iterator) {  console.log(value);}// 2// 3// The iterator is used up.// This loop will execute no iterations.for (const value of iterator) {  console.log(value);}// [No output]

Generators implement thereturn() method, which causes the generator function to early return when the loop exits. This makes generators not reusable between loops.

js
function* source() {  yield 1;  yield 2;  yield 3;}const generator = source();for (const value of generator) {  console.log(value);  if (value === 1) {    break;  }  console.log("This string will not be logged.");}// 1// The generator is used up.// This loop will execute no iterations.for (const value of generator) {  console.log(value);}// [No output]

Difference between for...of and for...in

Bothfor...in andfor...of statements iterate over something. The main difference between them is in what they iterate over.

Thefor...in statement iterates over theenumerable string properties of an object, while thefor...of statement iterates over values that theiterable object defines to be iterated over.

The following example shows the difference between afor...of loop and afor...in loop when used with anArray.

js
Object.prototype.objCustom = function () {};Array.prototype.arrCustom = function () {};const iterable = [3, 5, 7];iterable.foo = "hello";for (const i in iterable) {  console.log(i);}// "0", "1", "2", "foo", "arrCustom", "objCustom"for (const i in iterable) {  if (Object.hasOwn(iterable, i)) {    console.log(i);  }}// "0" "1" "2" "foo"for (const i of iterable) {  console.log(i);}// 3 5 7

The objectiterable inherits the propertiesobjCustom andarrCustom because it contains bothObject.prototype andArray.prototype in itsprototype chain.

Thefor...in loop logs onlyenumerable properties of theiterable object. It doesn't log arrayelements3,5,7 or"hello" because those are notproperties — they arevalues. It logs arrayindexes as well asarrCustom andobjCustom, which are actual properties. If you're not sure why these properties are iterated over, there's a more thorough explanation of howarray iteration andfor...in work.

The second loop is similar to the first one, but it usesObject.hasOwn() to check if the found enumerable property is the object's own, i.e., not inherited. If it is, the property is logged. Properties0,1,2 andfoo are logged because they are own properties. PropertiesarrCustom andobjCustom are not logged because they are inherited.

Thefor...of loop iterates and logsvalues thatiterable, as an array (which isiterable), defines to be iterated over. The object'selements3,5,7 are shown, but none of the object'sproperties are.

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-for-in-and-for-of-statements

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp