Skip to Content
JavaScript: The Definitive Guide, 7th Edition
book

JavaScript: The Definitive Guide, 7th Edition

by David Flanagan
May 2020
Intermediate to advanced
706 pages
21h 15m
English
O'Reilly Media, Inc.
Book available
Content preview from JavaScript: The Definitive Guide, 7th Edition

Chapter 12. Iterators and Generators

Iterable objects and their associated iterators are a feature of ES6 that we’ve seen several times throughout this book. Arrays (including TypedArrays) are iterable, as are strings and Set and Map objects. This means that the contents of these data structures can be iterated—looped over—with the for/of loop, as we saw in §5.4.4:

let sum = 0;
for(let i of [1,2,3]) { // Loop once for each of these values
    sum += i;
}
sum   // => 6

Iterators can also be used with the ... operator to expand or “spread” an iterable object into an array initializer or function invocation, as we saw in §7.1.2:

let chars = [..."abcd"]; // chars == ["a", "b", "c", "d"]
let data = [1, 2, 3, 4, 5];
Math.max(...data)        // => 5

Iterators can be used with destructuring assignment:

let purpleHaze = Uint8Array.of(255, 0, 255, 128);
let [r, g, b, a] = purpleHaze; // a == 128

When you iterate a Map object, the returned values are [key, value] pairs, which work well with destructuring assignment in a for/of loop:

let m = new Map([["one", 1], ["two", 2]]);
for(let [k,v] of m) console.log(k, v); // Logs 'one 1' and 'two 2'

If you want to iterate just the keys or just the values rather than the pairs, you can use the keys() and values() methods:

[...m]            // => [["one", 1], ["two", 2]]: default iteration
[...m.entries()]  // => [["one", 1], ["two", 2]]: entries() method is the same
[...m.keys()]     // => ["one", "two"]: keys() method iterates just map keys
[...m.values()]   // => [1, 2]: values() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern JavaScript from The Beginning [Second Edition] - Second Edition

Modern JavaScript from The Beginning [Second Edition] - Second Edition

Brad Traversy
JavaScript from Beginner to Professional

JavaScript from Beginner to Professional

Rob Percival, Laurence Svekis, Maaike van Putten, Codestars By Rob Percival

Publisher Resources

ISBN: 9781491952016Errata PageSupplemental Content