array[Symbol.iterator]() is the special method that makes an array iterable. JavaScript calls it for for...of, spread [...array], destructuring, and Array.from(array).
For arrays it is the same function as values(). You rarely call it by hand.
Syntax
Usually used through for...of or spread. You can also call it with square brackets.
JavaScript
const nums = [10, 20, 30];
for (const n of nums) {
console.log(n);
}
const iterator = nums[Symbol.iterator]();
console.log(iterator.next().value);
Call
What it does
for (const x of array)
Loop values; the loop calls [Symbol.iterator]().
[...array]
Spread values into a new array.
array[Symbol.iterator]()
Get the iterator object yourself.
Standard ES2015 method on Array.prototype. Same function as values().
Parameters
Parameter
Description
(none)
Call as array[Symbol.iterator]() with no arguments.
Return Value
Return Value
Description
Array Iterator
Iterator of element values in index order. Each next() returns { value, done }.
JavaScript Examples
Example 1 — for...of and Spread
Everyday features that call the iterator for you.
JavaScript
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log("Loop: " + color);
}
console.log("Spread: " + [...colors].join(", "));