Loading

T5 Modern JavaScript (ES6 and later) · Lesson 6

Iterators and higher-order functions

Functions that take or give back functions, and chains of array methods that say what is wanted instead of how to walk there; sorting names with localeCompare; patterns in text with regular expressions; the iteration protocol behind for...of and spread; generators that hand out one value at a time; and objects of your own that for...of can walk through.

  • write higher-order functions that take a function or return one
  • chain filter, map, reduce, find and flatMap, and sort numbers and names correctly
  • test, find and replace patterns in text with regular expressions
  • say how for...of and spread step through a value, with Symbol.iterator and next
  • write generators that yield values one at a time, even without end
  • make an object or a class of your own that for...of and spread can step through
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06); Google Chrome on the laptop (the kit renders every HTML block in it, and the DevTools step describes its panels) 155 (2026-11-06)Play this lesson's games

The back cover

Much of modern JavaScript hands functions to other functions: a rule for sorting, a test for filtering, a step for each item. The code then says what is wanted, not how to walk there, and reads almost like a sentence.

These pages show functions that take and give back functions, and chains of array methods for finding and sorting. They show regular expressions, which describe shapes of text. They show how for...of walks a value, how generators make values one at a time, and how an object of your own can be walked.

Before you start

The story: A morning of copying

The tower keeps a log of every bell it rings: thousands of lines, one for each stroke, with the bell, the hour and the ringer. Every morning an apprentice copies out the north bell's lines by hand, counts its strokes, and writes the ringers' names in order. It takes the whole morning. Today the count came out wrong twice.

And the roster put asha after Zubin, because that one name had been written in small letters.

Master Hakim Verge reads the roster and sighs. "A loop you write by hand every morning is a loop you can get wrong every morning," he says. "Let the list do the walking. You only say what is to be done with each line."

Most programs spend their time going through lists: orders, students, lines of a log. A for loop can do all of it, and it makes you say how to walk the list each time. Modern JavaScript lets you say what you want from the list instead, with functions that take other functions. Underneath, one small agreement, the iteration protocol, lets for...of and spread walk arrays, strings, and objects of your own.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Functions as values.say(text, shout), shout with no bracketsFunctions that take and return functions.
Higher-order functions and callbacks.list.map((x) => x * 2)Writing your own.
map, filter and reduce.prices.reduce((s, p) => s + p, 0)Chained together.
Sorting with a compare function.nums.toSorted((x, y) => x - y)Sorting names with localeCompare.
Closures.A counter that remembers its count.A function that remembers a setting.
for...of.for (const item of items)How it walks a value.
Spread and rest.[...a, ...b], (...args) =>Spread walks values the same way.
Classes.class Range { ... }A class that for...of can walk.
String methods."a,b".split(","), replaceAllWith patterns instead of fixed text.
Escape sequences.\n and \\Backslashes in patterns.

By the end of this lesson you will be able to:

  • write higher-order functions that take a function or return one;
  • chain filter, map, reduce, find and flatMap, and sort numbers and names correctly;
  • test, find and replace patterns in text with regular expressions;
  • say how for...of and spread step through a value, with Symbol.iterator and next;
  • write generators that yield values one at a time, even without end;
  • make an object or a class of your own that for...of and spread can step through.

How to follow this lesson

Read each chain of methods aloud, from left to right, as a sentence: keep the orders of more than one, turn each into its cost, add the costs up. If the sentence makes sense, the chain usually does too.

In one line

This lesson is about saying what you want from a list, with functions that take functions, and about the iteration protocol that lets for...of walk anything that follows it.

Functions that take and give functions

At a glance

A food processor does one job, chopping, but a new blade changes what it chops. The machine is the pattern, the blade is the detail. A function can be built the same way, with the detail plugged in from outside.

A higher-order function takes a function, gives one back, or both. Taking one plugs a detail into a pattern of work, as sort takes a rule for comparing. Giving one back remembers a setting in a closure. And a function called pipe can join small functions into one, each handing its result to the next.

Take a guess: Where does the name currying, for a function that returns a function, come from?

The functions lesson defined a higher-order function: one that takes a function as an argument, or gives one back. map, filter and reduce take one. Now you will write your own, of both kinds, because they turn a pattern you keep repeating into one function you write once.

Taking a function

A function that does something a number of times needs to be told what to do. That something is a function, handed in as an argument:

function repeat(times, action) {
  for (let i = 1; i <= times; i++) action(i);
}
repeat(3, (n) => console.log(`bell ${n}`));
bell 1
bell 2
bell 3

repeat knows how to count; the arrow knows what a bell says. Neither has to know about the other. That separation is the whole point: the counting is written once, and any action can be plugged into it.

Giving back a function

A shop runs sales of different sizes: 10% off, 20% off during the festival. A function can make a pricing function for each size of sale, and the size is remembered by a closure, as the scope lesson showed:

function discount(percent) {
  return (price) => price - (price * percent) / 100;
}
const festival = discount(20);
console.log(festival(500), discount(10)(500));
400 450

festival is a function that knows its percent is 20; it takes a price and gives the sale price. discount(10)(500) makes a 10% function and calls it at once, which reads oddly but shows that the result of discount really is a function.

Here is a useful one from real code. once takes any function and gives back a guarded version that does its work only the first time, however often it is called. A payment button that a customer taps twice should charge once:

function once(fn) {
  let done = false;
  let result;
  return (...args) => {
    if (!done) {
      done = true;
      result = fn(...args);
    }
    return result;
  };
}
const pay = once((amount) => {
  console.log(`charging ₹${amount}`);
  return "paid";
});
console.log(pay(450), pay(450));
charging ₹450
paid paid

The rest parameter gathers whatever arguments arrive, and spread passes them on, so once works for any function, with any arguments. The card was charged once, and both taps got the answer paid.

Joining small functions into one

Small functions with one job each can be joined into a pipeline, each passing its answer to the next. A pipe function does the joining, and reduce does the walking:

const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
const addGst = (p) => p * 1.18;
const round = (p) => Math.round(p);
const label = (p) => `₹${p}`;
console.log(pipe(addGst, round, label)(99));
₹117

99 with GST is 116.82; rounded, 117; labelled, ₹117. Each step can be tested alone, and the order of the steps reads in one line.

KindExampleUsed for
takes a functionrepeat(3, action), list.map(fn)a pattern of work, with the detail plugged in
gives back a functiondiscount(20)a function with a setting remembered
bothonce(fn), pipe(f, g, h)changing or joining functions

Worked example 1

A cab app adds a night charge of 25% after 10 pm and a 5% airport fee for airport rides. Write a function surcharge(percent) that makes a function adding that percent, and use pipe to price a ₹400 night ride to the airport, rounded to whole rupees.

What we have: a base fare, two percentages, and pipe

What we need: the final fare for a night airport ride

The plan: surcharge returns a function that adds its percent; pipe joins the night charge, the airport fee and rounding

const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
const surcharge = (percent) => (fare) => fare + (fare * percent) / 100;
const night = surcharge(25);
const airport = surcharge(5);
const nightAirport = pipe(night, airport, Math.round);
console.log(nightAirport(400));
525

The ride costs ₹525.

Check: 400 + 25% = 500; 500 + 5% = 525; already whole.

A path that fails: writing a separate function for every mix of charges, such as nightAirportFare and nightCityFare. With three charges there are already eight mixes, and every change of rate must be made in all of them.

When you are stuck: a higher-order function gives a function where you wanted a value

If the result prints as code or as [Function], you have the function, not its answer: call it.

discount(20) gives a function; discount(20)(500) gives a price.

When passing a function, leave the brackets off: repeat(3, ring), not repeat(3, ring()).

Print typeof of the value to see whether it is a function.

Your turn

const times = (n) => (x) => x * n;
const double = times(2);
console.log(double(21), times(3)(5), typeof times(4));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
42 15 function
  1. double is times with n = 2: 21 × 2 = 42.
  2. times(3)(5) is 5 × 3 = 15.
  3. times(4) is a function, not yet called.

It prints 42 15 function.

Write twice(fn), which gives back a function that calls fn two times.Tap to reveal
const twice = (fn) => () => {
  fn();
  fn();
};
twice(() => console.log("ding"))();
ding
ding

Calling the result runs fn twice.

Why does once need a closure?Tap to reveal
  1. It must remember whether fn has run, between calls.
  2. done and result live in once's scope, kept by the returned arrow.

Because done and result must survive between calls.

Did you know?

Functions about functions, 1930s

Functions that take and return functions come from mathematics. Alonzo Church introduced the lambda calculus in the 1930s, as part of research into the foundations of mathematics. The Stanford Encyclopedia of Philosophy calls it, at heart, a simple notation for functions and application, built on two ideas: applying a function to an argument, and forming new functions.

Why it fits here: It gives this topic's higher-order functions their root: functions treated as values began in a 1930s notation for mathematics.

Sources: Wikipedia: Lambda calculus; Stanford Encyclopedia of Philosophy: The Lambda Calculus

One logician, two names

Turning f(a, b) into f(a)(b), one function per argument, is called currying, after the logician Haskell Curry. A programming language carries the first name too: the Haskell report says the language is named after the logician Haskell B. Curry, whose work provides the logical basis for much of it. So one logician named both a technique and a language.

Why it fits here: It answers this topic's question: a function that gives back a function, one argument at a time, is called currying after Haskell Curry.

Sources: Wikipedia: Currying; Haskell 2010 Language Report: Preface

In one line

A higher-order function takes a function, gives one back, or both. Taking one plugs a detail into a pattern of work; giving one back remembers a setting in a closure; pipe joins small functions into one.

Chains, finding and sorting

At a glance

A good instruction reads as a sentence: from the orders, keep the paid ones, take their totals, add them up. Array methods chained one after another read the same way.

Each method hands its result to the next. The methods find and findIndex stop at the first match. Sort numbers by subtracting one from the other, and sort names with localeCompare, which follows a language's dictionary and takes a locale and options. A chain is easiest to read with one method on each line.

Take a guess: Does ä come before z or after it, and does the answer depend on the language?

Each array method that gives back an array can be followed by another, in a chain. A canteen wants the money taken on orders of more than one plate:

const orders = [
  { item: "tea", qty: 2, price: 15 },
  { item: "dosa", qty: 1, price: 80 },
  { item: "vada", qty: 3, price: 20 },
];
const total = orders
  .filter((o) => o.qty > 1)
  .map((o) => o.qty * o.price)
  .reduce((sum, x) => sum + x, 0);
console.log(total);
90

Read it as a sentence: keep the orders with more than one plate, turn each into its cost, add the costs up. filter keeps tea and vada; map gives 30 and 60; reduce adds them to 90. Writing each method on its own line, starting with the dot, keeps a long chain readable.

Finding one item

filter gives every match. When you want only one, the find family stops at the first:

const nums = [5, 12, 8, 130, 44];
console.log(nums.find((n) => n > 10), nums.findIndex((n) => n > 10), nums.findLast((n) => n > 10), nums.find((n) => n > 500));
12 1 44 undefined
MethodGivesWhen nothing matches
find(test)the first item that passesundefined
findIndex(test)its index-1
findLast(test)the last item that passesundefined
some(test)true if any item passesfalse

A find that misses gives undefined, so check before using what it found, as lesson 03's mistakes showed.

Flattening while mapping

flatMap maps each item to an array and joins all the arrays into one. It suits data where each item holds a list:

const sections = [["Asha", "Ravi"], ["Meera"]];
console.log(sections.flatMap((s) => s), ["a b", "c"].flatMap((s) => s.split(" ")));
[ 'Asha', 'Ravi', 'Meera' ] [ 'a', 'b', 'c' ]

Sorting names: localeCompare

The arrays lesson showed that a sort with no compare function compares the characters' codes. For names typed by real people, that goes wrong in two ways: capitals come before every small letter, and letters with accents come after z:

const names = ["ravi", "Asha", "Élise", "zoya"];
console.log(names.toSorted(), names.toSorted((a, b) => a.localeCompare(b)));
[ 'Asha', 'ravi', 'zoya', 'Élise' ] [ 'Asha', 'Élise', 'ravi', 'zoya' ]
localeCompare

A string method, a.localeCompare(b), that compares two strings the way a language's dictionary would. It gives a negative number when a comes first, a positive one when b comes first, and 0 when they are the same, which is exactly what a compare function must give.

console.log("a".localeCompare("b"), "b".localeCompare("a"), "a".localeCompare("a"));
-1 1 0

Like toLocaleString in the template literals lesson, localeCompare takes a locale. Hindi words sort in the order of the Devanagari alphabet with "hi", and the option numeric: true sorts the numbers inside text by their value, so file2 comes before file10:

const words = ["मीरा", "आशा", "रवि", "कबीर"];
console.log(words.toSorted((a, b) => a.localeCompare(b, "hi")));
const files = ["file10", "file2", "file1"];
console.log(files.toSorted(), files.toSorted((a, b) => a.localeCompare(b, "en", { numeric: true })));
[ 'आशा', 'कबीर', 'मीरा', 'रवि' ]
[ 'file1', 'file10', 'file2' ] [ 'file1', 'file2', 'file10' ]

For a long list, Intl.Collator makes a comparer once, with its locale and options, and its compare method is handed straight to toSorted:

const byName = new Intl.Collator("en-IN");
console.log(["ravi", "Asha", "meera"].toSorted(byName.compare));
[ 'Asha', 'meera', 'ravi' ]

Worked example 2

A school's list must be sorted by class, and within a class by name, in alphabet order whatever the capitals. Sort four students that way.

What we have: students with a name and a class number

What we need: the names in order of class, then name

The plan: compare classes by subtracting; when they are equal, the subtraction gives 0, and || moves on to localeCompare of the names

const students = [
  { name: "Ravi", cls: 10 },
  { name: "asha", cls: 9 },
  { name: "Meera", cls: 10 },
  { name: "Kabir", cls: 9 },
];
const sorted = students.toSorted((a, b) => a.cls - b.cls || a.name.localeCompare(b.name));
console.log(sorted.map((s) => `${s.cls} ${s.name}`));
[ '9 asha', '9 Kabir', '10 Meera', '10 Ravi' ]

Class 9 comes first, asha then Kabir, and then class 10, Meera then Ravi.

Check: asha comes before Kabir although it starts with a small letter, because localeCompare ignores the case at first.

A path that fails: sorting by name with the default sort, then by class. The default puts Kabir before asha, as K is a capital, and a second sort may undo the first.

When you are stuck: a chain or a sort gives the wrong result

Print the array after each step of the chain, one link at a time.

find gives undefined and findIndex −1 when nothing matches: check before using them.

Numbers need a compare function, (a, b) => a - b; names need localeCompare.

For several keys, join the comparisons with ||: the first that is not 0 decides.

Your turn

const words = ["banana", "Apple", "cherry"];
console.log(words.toSorted()[0], words.toSorted((a, b) => a.localeCompare(b))[2]);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Apple cherry
  1. Default sort: capital A comes first.
  2. With localeCompare: apple, banana, cherry; the last is cherry.

It prints Apple cherry.

Which method gives the index of the first price over 100 in prices?Tap to reveal
  1. find gives the item; findIndex gives its place.

prices.findIndex((p) => p > 100)

What does "b".localeCompare("a") give, and what does it mean to toSorted?Tap to reveal
  1. A positive number means b comes after a.

1: put "a" first.

Did you know?

The same letters, two orders

Sorting words depends on the language. MDN's example of localeCompare shows ä sorting before z in German, but after z in Swedish. The Unicode Collation Algorithm, the standard behind such sorting, puts it in one line: Germans, French and Swedes sort the same characters differently. It adds that even within one language, dictionaries may sort differently from phone books.

Why it fits here: It answers this topic's question, and explains why localeCompare takes a locale: the right order depends on the reader's language.

Sources: MDN: String.prototype.localeCompare(); Unicode Technical Standard #10: Unicode Collation Algorithm

Searching from the end

Searching an array from its end got methods of its own only recently. TC39's list of finished proposals names Array find from last, by Wenlu Wang, which added findLast and findLastIndex beside find and findIndex. MDN shows findLast working across browsers since August 2022. Before them, code reversed a copy of the array first, or wrote a loop that counted down.

Why it fits here: It completes this topic's find and findIndex: findLast and findLastIndex search the same way, starting from the end.

Sources: TC39: Finished Proposals; MDN: Array.prototype.findLast()

In one line

Chain array methods and read them as a sentence. find and findIndex stop at the first match. Sort numbers by subtracting one from the other, and names with localeCompare, which follows a language's dictionary and takes a locale and options.

Patterns in text: regular expressions

At a glance

A PIN code is six digits, an Indian mobile number ten, a date two digits, two digits and four. Each is a shape of text, and a regular expression describes such a shape.

In a pattern, \d is a digit, + means one or more, {6} exactly six, and ^ and $ mark the ends. The method test checks a text, and match finds parts of it. The method replace changes them, with the g flag for every match or a function for each, and split cuts a text into pieces.

Take a guess: Can one regular expression slow down a whole network?

An Indian PIN code is six digits. Checking that with indexes and loops takes a dozen lines. A regular expression describes the shape in one:

Regular expression

A pattern for text, written between slashes, such as /^\d{6}$/. Methods such as test, match, replace and split use it to check, find, change or cut text that has that shape.

console.log(/^\d{6}$/.test("411001"), /^\d{6}$/.test("4110"), /^\d{6}$/.test("41100a"));
true false false

Read the pattern one piece at a time. ^ means the start of the text. \d means any digit. {6} means exactly six of what comes before. $ means the end. So the whole text must be six digits and nothing else: 4110 is too short, and 41100a has a letter.

PieceMatchesExample
\done digit/\d/ finds the 4 in A4
\sone space, tab or line break/\s+/ finds a run of spaces
[A-Z]one capital letter/[A-Z]{2}/ finds MH
+, {6}, {1,2}one or more; exactly six; one or two/\d+/ finds 450
^ and $the start and the end of the text/^\d{6}$/: six digits, nothing else
( )a group, remembered for later/(\d{5}) ?(\d{5})/
g and i after the last slashevery match; ignore capitals/cat/gi

Finding and changing

match with the g flag gives every match as an array; without g it gives the first, with details. replace with a pattern and the g flag changes every match:

const text = "Tea ₹15, dosa ₹80, vada ₹20";
console.log(text.match(/\d+/g));
console.log("a.b.c".replace(".", "-"), "a.b.c".replace(/\./g, "-"));
[ '15', '80', '20' ]
a-b.c a-b-c

With fixed text, replace changes only the first match: a-b.c. With a pattern and g, every one. The dot needs a backslash in the pattern, \., because a bare dot in a pattern means any character.

replace is a higher-order function too: instead of fixed text it can take a function, which receives each match and returns its replacement. Here every price is doubled for a festival menu:

const text = "Tea 15, dosa 80";
console.log(text.replace(/\d+/g, (n) => `₹${Number(n) * 2}`));
Tea ₹30, dosa ₹160

Groups, written in round brackets, remember parts of a match. In a replacement text, $1 and $2 stand for the first and second groups:

const phone = /^(\d{5}) ?(\d{5})$/;
const m = "98765 43210".match(phone);
console.log(m[1], m[2], "9876543210".replace(phone, "$1 $2"));
console.log("Pune, Mumbai,  Nagpur".split(/,\s*/));
98765 43210 98765 43210
[ 'Pune', 'Mumbai', 'Nagpur' ]

In the phone pattern, the space is followed by ?, which means zero or one of what comes before. So the pattern accepts the number with or without its space, and the replacement writes it with one. The method split, given a pattern, cuts at a comma followed by any number of spaces, so the double space before Nagpur does no harm.

Worked example 3

A housing society's parking app must accept vehicle numbers such as MH12AB1234: two capital letters, two digits, one or two capital letters, four digits. Guards often type spaces. Remove the spaces, make the letters capital, and check the shape.

What we have: vehicle numbers as typed, some with spaces or small letters

What we need: true for a number of the right shape, false otherwise

The plan: replace every run of spaces with nothing, toUpperCase, then test against a pattern with ^ and $

const vehicle = /^[A-Z]{2}\d{2}[A-Z]{1,2}\d{4}$/;
const ok = (typed) => vehicle.test(typed.replace(/\s+/g, "").toUpperCase());
console.log(ok("MH12AB1234"), ok("mh 12 ab 1234"), ok("MH12A1234"), ok("M12AB1234"));
true true true false

The first three are accepted; M12AB1234, with one letter at the start, is refused.

Check: MH12A1234 is accepted because the middle part may have one or two letters.

A path that fails: a pattern without ^ and $. Then /[A-Z]{2}\d{2}[A-Z]{1,2}\d{4}/ finds a good number inside a longer, wrong text, such as XMH12AB12345, and says true.

Small patterns only

Regular expressions are powerful and quickly become hard to read. Keep each one small, give it a name in a const, and test it with good and bad examples, as the parking example does. MDN's guide to regular expressions lists every piece when you need more.

When you are stuck: a pattern matches too much or too little

Test it with test() on a good and a bad example, one change at a time.

Add ^ and $ when the whole text must match, not just a part.

Add g to match or replace every match, not just the first.

A dot matches any character: write \. for a real dot.

Your turn

console.log(/^\d{3}$/.test("123"), /\d{3}/.test("x1234"), "2,000".replace(/,/g, ""));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
true true 2000
  1. 123 is three digits and nothing else.
  2. Without ^ and $, the pattern finds 123 inside x1234.
  3. Every comma is removed.

It prints true true 2000.

Write a pattern that matches a text made only of one or more digits.Tap to reveal
  1. Start, one or more digits, end.

/^\d+$/

How do you change every number in a text to [n], using replace?Tap to reveal
  1. A pattern with g finds every number.
  2. The replacement can be fixed text.

text.replace(/\d+/g, "[n]")

Did you know?

Borrowed from Perl

JavaScript's regular expressions were not invented for it. The standard states that their form and functionality are modelled after the regular expression facility in the Perl 5 programming language. So \d, + and {6} mean in JavaScript what they mean in Perl, and a pattern learnt for one often reads the same in the other.

Why it fits here: It explains where this topic's pattern symbols come from: JavaScript took them from Perl 5.

Source: ECMAScript Language Specification: RegExp (Regular Expression) Objects

A pattern that slowed a network

One regular expression once slowed a large part of the web. On 2 July 2019 Cloudflare deployed a new firewall rule that exhausted every processor core handling web traffic across its network. Its report gives the cause: the update contained a regular expression that backtracked enormously, trying so many ways to match that the processors had no time left for anything else.

Why it fits here: It answers this topic's question: a badly built pattern can take a very long time on some text, so test patterns on long inputs too.

Source: Cloudflare Blog: Details of the Cloudflare outage on July 2, 2019

In one line

A regular expression describes a shape of text: \d a digit, + one or more, {6} exactly six, ^ and $ the ends. test checks, match finds, replace changes (the g flag for every match, a function for each), and split cuts.

How for...of walks a value

At a glance

A ticket collector walks down a train, asking each passenger in turn, and stops at the last coach. A for...of loop walks a value the same way, asking for one item at a time.

Behind for...of, spread, destructuring and Array.from is one protocol. Each asks the value for an iterator, through its Symbol.iterator method, and calls next until it reports done. Arrays and strings are iterable, plain objects are not, and an iterator is used up after one walk. A second walk needs a new iterator.

Take a guess: Did another language use an iterator protocol for its for loops before JavaScript did?

for...of works on arrays and strings, and spread does too. Neither knows anything special about arrays. Both follow one small agreement, which any value can join: the iteration protocol.

Iterator

An object with a method next(). Each call gives the next value, wrapped as { value, done }: done is false while values remain, and true once they have run out.

Iterable

A value that can give an iterator, through a method stored under the special key Symbol.iterator. Arrays, strings, Maps and Sets are iterable; plain objects are not.

Ask an array for its iterator, and call next by hand, as for...of does behind the scenes:

const it = [10, 20][Symbol.iterator]();
console.log(it.next(), it.next(), it.next());
{ value: 10, done: false } { value: 20, done: false } { value: undefined, done: true }

Two values, then done. for...of is a loop that does exactly this: get the iterator, call next, run the body with each value, and stop at done. A string's iterator gives its characters:

const it = "hi"[Symbol.iterator]();
console.log(it.next().value, it.next().value, it.next().done);
h i true

What is not iterable

A plain object has no Symbol.iterator method, so for...of refuses it, with a message that uses this lesson's word:

const marks = { maths: 88 };
for (const m of marks) console.log(m);
Uncaught TypeError: marks is not iterable
    at line 2

This is the same TypeError that lesson 03 met when an object was spread into an array. The fix is the same: walk Object.entries(marks), Object.keys or Object.values, which are arrays.

An iterator is used up

An iterator remembers how far it has got. Once it is done, it stays done, so walking the same iterator twice gives nothing the second time. values() gives an array's iterator directly:

const it = [1, 2, 3].values();
console.log(typeof it.next, [...it], [...it]);
function [ 1, 2, 3 ] []

The array itself can be walked any number of times, because each for...of or spread asks it for a fresh iterator. The iterator from values() was walked once, and was empty after that.

Array.from: any iterable into an array

Array.from walks any iterable and collects the values into a new array, with a map function as an optional second argument. It also accepts an object with a length, which makes it a quick way to build a numbered list:

console.log(Array.from({ length: 5 }, (_, i) => i + 1), Array.from("chai"), Array.from(new Set([1, 1, 2])));
[ 1, 2, 3, 4, 5 ] [ 'c', 'h', 'a', 'i' ] [ 1, 2 ]

The underscore is a name for the first argument, which this arrow does not use; i is the index. A Set, which the maps and sets lesson meets, keeps each value once, so the repeated 1 appears once.

Uses the protocolExample
for...offor (const x of list)
spread[...list], Math.max(...list)
array destructuringconst [a, b] = list;
Array.fromArray.from(list)

Worked example 4

A cinema's seats in row C are numbered 1 to 12. Make the seat names C1 to C12 without writing a loop, and pick out the ones on the aisle, the first and the last.

What we have: a row letter and a count of seats

What we need: an array of twelve seat names, and the two aisle seats

The plan: Array.from with a length of 12 and a map function builds the names; array destructuring and at(-1) take the ends

const seats = Array.from({ length: 12 }, (_, i) => `C${i + 1}`);
const [first] = seats;
console.log(seats.length, first, seats.at(-1), seats.slice(0, 3));
12 C1 C12 [ 'C1', 'C2', 'C3' ]

Twelve seats, from C1 to C12, with C1 and C12 on the aisle.

Check: i runs from 0 to 11, so i + 1 runs from 1 to 12.

A path that fails: Array.from({ length: 12 }, (i) => `C${i}`). The first argument is the item, which is undefined here, not the index, so every seat is called Cundefined.

When you are stuck: for...of or spread refuses a value

"is not iterable" means the value has no Symbol.iterator: a plain object, a number, null or undefined.

For an object, walk Object.entries, Object.keys or Object.values.

If a second walk gives nothing, you are walking a used iterator: walk the array, or make a new iterator.

Print the value first: it may not be what you think.

Your turn

const it = ["a", "b"][Symbol.iterator]();
it.next();
console.log(it.next().value, it.next().done, [...it].length);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
b true 0
  1. The first next gave a.
  2. The second gives b; the third is done.
  3. Nothing is left to spread.

It prints b true 0.

Why can for...of walk a string but not { a: 1 }?Tap to reveal
  1. Strings have a Symbol.iterator method.
  2. Plain objects do not.

Because strings are iterable and plain objects are not.

Build the array [2, 4, 6, 8] with Array.from.Tap to reveal
console.log(Array.from({ length: 4 }, (_, i) => (i + 1) * 2));
[ 2, 4, 6, 8 ]

Array.from({ length: 4 }, (_, i) => (i + 1) * 2)

Did you know?

Python's iterators, 2001

JavaScript's iteration protocol has an older cousin. Python's PEP 234, created on 30 January 2001 by Ka-Ping Yee and Guido van Rossum, proposed an iteration interface that objects can provide to control the behaviour of for loops: a method that produces an iterator object. JavaScript's Symbol.iterator, which returns an object with a next method, works on the same plan.

Why it fits here: It answers this topic's question: Python's for loops asked objects for iterators years before JavaScript's for...of did.

Source: Python: PEP 234, Iterators

map and filter for any iterator

Iterators gained array-like methods in 2025. TC39's list of finished proposals names Sync Iterator helpers, and MDN shows Iterator.prototype.map working in the latest browsers since March 2025. So map, filter and take can now run on any iterator, such as one from a generator, without first copying its values into an array.

Why it fits here: It extends this topic's chains to iterators: the array methods now have iterator versions that work one value at a time.

Sources: TC39: Finished Proposals; MDN: Iterator.prototype.map()

In one line

for...of, spread, destructuring and Array.from all ask a value for an iterator through Symbol.iterator, and call next until done is true. Arrays and strings are iterable, plain objects are not, and an iterator is used up after one walk.

Generators: values one at a time

At a glance

A storyteller does not tell the whole story at once; each evening brings one more chapter, and the story waits in between. A generator gives its values the same way.

A generator function, written function*, gives back an iterator. Each call of next runs the body to the next yield and pauses there, keeping every local name, until next is called again. A generator can describe values without end, such as every even number, as long as you take only as many as you need.

Take a guess: Which language had a yield statement for its iterators, years before JavaScript?

Writing an iterator by hand means writing next, keeping count, and building { value, done } objects. A generator function writes all of that for you. You write an ordinary-looking function, and wherever it has a value to give, it says yield.

Generator function

A function written function* name() { ... }, with a star. Calling it runs none of its body; it gives back a generator, an iterator. Each next runs the body up to the next yield value, hands out that value, and pauses there.

function* tickets() {
  yield "T1";
  yield "T2";
  yield "T3";
}
console.log([...tickets()]);
const g = tickets();
console.log(g.next(), g.next().value);
[ 'T1', 'T2', 'T3' ]
{ value: 'T1', done: false } T2

Spread walked the whole generator and collected three tickets. A second generator, g, was walked by hand: the first next ran the body to the first yield and paused there with T1; the second next carried on to the second yield.

A generator starts only when asked

Calling a generator function does not run its body. The body starts at the first next, and stops again at each yield. This print order shows it:

function* gen() {
  console.log("started");
  yield 1;
}
const g = gen();
console.log("made");
console.log(g.next().value);
made
started
1

Values without end

Because a generator pauses at every yield, it can describe a list that never ends, and still hand out only as many values as are asked for. A ticket counter that starts at 101 needs no last number:

function* counter(start) {
  let n = start;
  while (true) {
    yield n;
    n++;
  }
}
const ids = counter(101);
console.log(ids.next().value, ids.next().value, ids.next().value);
101 102 103

while (true) would be an endless loop in an ordinary function, and freeze the page. In a generator it is safe, because the loop stops at each yield until the next value is wanted. Never spread an endless generator, though: spread wants every value, and there is no last one. Take a few instead, with a small generator of your own:

function* take(iterable, count) {
  let i = 0;
  for (const x of iterable) {
    if (i >= count) return;
    yield x;
    i++;
  }
}
function* naturals() {
  let n = 1;
  while (true) yield n++;
}
console.log([...take(naturals(), 5)]);
[ 1, 2, 3, 4, 5 ]

take walks any iterable with for...of and stops, with return, after count values. Spread now stops too, because take is done after five.

Ordinary functionGenerator function
function f() { ... }function* g() { ... }
runs its whole body when calledcalling it gives a generator; the body runs bit by bit
gives one result with returngives many values with yield, one per next
an endless loop freezes the pagean endless loop is fine, as it pauses at each yield

Worked example 5

The Clock Tower's log is too long to read into memory at once. Write a generator that walks the log's lines and yields only the north bell's, and use it to count the north bell's strokes without building a second array.

What we have: a list of log lines, each with a bell and its strokes

What we need: the north bell's total strokes

The plan: a generator walks the lines and yields each north line; a for...of over it adds the strokes

const log = [
  { bell: "north", strokes: 3 },
  { bell: "south", strokes: 2 },
  { bell: "north", strokes: 6 },
];
function* linesFor(lines, bell) {
  for (const line of lines) {
    if (line.bell === bell) yield line;
  }
}
let total = 0;
for (const line of linesFor(log, "north")) total += line.strokes;
console.log(total);
9

The north bell struck 9 times.

Check: 3 + 6 = 9; the south bell's 2 strokes were never yielded.

A path that fails: spreading an endless log, such as one that a generator keeps reading as new lines arrive, into an array first. The spread never finishes, as the log has no end.

When you are stuck: a generator does not do what you expect

Nothing happens when you call it? That is right: call next, or walk it with for...of.

Forgot the star? Without function*, yield is an error.

A second walk gives nothing? A generator is used up: call the generator function again for a new one.

An endless generator must be walked with a limit, such as take, never spread whole.

Your turn

function* abc() {
  yield "a";
  yield "b";
}
const g = abc();
console.log(g.next().value, [...g], [...abc()]);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
a [ 'b' ] [ 'a', 'b' ]
  1. The first next gives a.
  2. Spread takes what is left of g: b.
  3. abc() is a new generator, walked from the start.

It prints a [ 'b' ] [ 'a', 'b' ].

Write a generator evens() that yields 2, 4, 6 and so on, without end.Tap to reveal
function* evens() {
  let n = 2;
  while (true) {
    yield n;
    n += 2;
  }
}
const e = evens();
console.log(e.next().value, e.next().value, e.next().value);
2 4 6

A while (true) loop with a yield inside.

Why is while (true) safe inside a generator?Tap to reveal
  1. The loop pauses at each yield.
  2. It only goes on when the next value is asked for.

Because it stops at every yield until next is called.

Did you know?

Async before async

Generators once did the work that async functions do now. The co library describes itself as generator based control flow for Node.js and the browser, using promises, letting you write non-blocking code. Inside it, a line such as var result = yield Promise.resolve(true) waited for a promise, much as await does today. Its readme calls it a stepping stone towards the async/await proposal.

Why it fits here: It shows how far this topic's generators reach: pausing at yield was the trick that later became await.

Source: co: README

yield came from CLU

The word yield is older than JavaScript. CLU, a language whose project Barbara Liskov led, had iterators that handed each value to the caller with a yield statement. Liskov's history of CLU counts its iterators among its interesting and influential features. Wikipedia dates generators in CLU to 1975 and notes that such iterators are now common, often called generators.

Why it fits here: It answers this topic's question: CLU paused and resumed with yield decades before JavaScript's generators did.

Sources: Barbara Liskov: A History of CLU; Wikipedia: CLU (programming language); Wikipedia: Generator (computer programming)

In one line

A generator function, function*, gives back an iterator; each next runs its body to the next yield and pauses there. It can describe values without end, as long as you take only as many as you need.

Objects that for...of can walk

At a glance

A library's catalogue lets any reader walk its books in order, without knowing how the shelves are built. An object of your own can offer the same kind of walk.

An object joins the iteration protocol with a method under Symbol.iterator that returns an iterator, usually written as a generator method, *[Symbol.iterator](). Inside it, yield* passes on another iterable's values one by one. Each walk calls the method again, so each starts afresh. Then for...of, spread and destructuring all work on the object.

Take a guess: Why can a generator method serve as an object's Symbol.iterator?

Any object can join the protocol: give it a method under the key Symbol.iterator that returns an iterator, and for...of, spread and Array.from will walk it. The easiest way to return an iterator is a generator, so the method is usually a generator method, written with a star before its name.

class Range {
  constructor(from, to) {
    this.from = from;
    this.to = to;
  }
  *[Symbol.iterator]() {
    for (let n = this.from; n <= this.to; n++) yield n;
  }
}
const r = new Range(3, 6);
console.log([...r], Math.max(...r));
for (const n of new Range(1, 2)) console.log(n);
[ 3, 4, 5, 6 ] 6
1
2

Read the method's name slowly. The square brackets make a computed name: the method is stored under the value of Symbol.iterator, a special key that JavaScript itself defines, rather than under a word. The star makes it a generator method. Every for...of or spread over a Range calls it, gets a fresh generator, and walks the numbers from from to to.

Unlike a generator, a Range can be walked any number of times, because each walk calls the method again. It also holds only two numbers, however long the range is: the values are made one at a time as they are asked for.

The same, without a generator

To see that nothing is hidden, here is an iterable written by hand, with a next method that returns { value, done } itself:

const seats = {
  rows: ["A", "B"],
  [Symbol.iterator]() {
    let i = 0;
    const rows = this.rows;
    return {
      next() {
        return i < rows.length ? { value: rows[i++], done: false } : { value: undefined, done: true };
      },
    };
  },
};
console.log([...seats]);
[ 'A', 'B' ]

It works, and it shows why generators exist: the counting, the objects and the end are all written by hand here, while the Range's generator method needed one line. In your own code, write the generator method.

Make an object iterable byCode
a generator method (usual)*[Symbol.iterator]() { yield ...; }
returning an iterator by hand[Symbol.iterator]() { return { next() { ... } }; }
returning another iterable's iterator[Symbol.iterator]() { return this.items[Symbol.iterator](); }

Worked example 6

A playlist for the school assembly holds its songs in a private field. Make the class iterable, so that for...of over a playlist walks its songs, and spread it to count them, without making the private list public.

What we have: a class with a private array of songs

What we need: for...of and spread working on the playlist itself

The plan: a generator method under Symbol.iterator yields each song from the private field, so the field stays private

class Playlist {
  #songs;
  constructor(...songs) {
    this.#songs = songs;
  }
  *[Symbol.iterator]() {
    yield* this.#songs;
  }
}
const assembly = new Playlist("Vande Mataram", "Hum Honge Kamyab", "Jana Gana Mana");
for (const song of assembly) console.log(song);
console.log([...assembly].length, assembly.songs);
Vande Mataram
Hum Honge Kamyab
Jana Gana Mana
3 undefined

The playlist walks its three songs, and its list stays private: assembly.songs is undefined.

Check: yield* hands out every value of another iterable, here the private array, one by one.

A path that fails: a getter that returns this.#songs, so that callers can loop over the array. Callers then hold the real array, and can push or remove songs from outside.

When you are stuck: your own object is not iterable

The method's key must be Symbol.iterator, in square brackets, not the word iterator.

A generator method needs the star: *[Symbol.iterator]().

A hand-made next must return { value, done } every time, with done true at the end.

yield* passes on every value of another iterable.

Your turn

class Countdown {
  constructor(from) {
    this.from = from;
  }
  *[Symbol.iterator]() {
    for (let n = this.from; n > 0; n--) yield n;
  }
}
console.log([...new Countdown(3)], Array.from(new Countdown(2)));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 3, 2, 1 ] [ 2, 1 ]
  1. The generator counts down while n is more than 0.
  2. Array.from walks it the same way as spread.

It prints [ 3, 2, 1 ] [ 2, 1 ].

Why is the method's name written [Symbol.iterator] and not iterator?Tap to reveal
  1. for...of looks for the method under the special key Symbol.iterator.
  2. The square brackets store it under that key's value.

Because the protocol's key is Symbol.iterator, a computed name.

What does yield* [1, 2] do inside a generator?Tap to reveal
  1. yield* hands out each value of another iterable.

It yields 1, then 2.

Did you know?

The hook for-of calls

Symbol.iterator is one of the standard's well-known symbols, a short list of hooks that built-in syntax looks for. The standard's table describes it as a method that returns the default iterator for an object, called by the semantics of the for-of statement. MDN adds that whenever an object needs to be iterated, this method is called with no arguments.

Why it fits here: It explains this topic's *[Symbol.iterator](): it is the one hook that for...of looks for on any object.

Sources: ECMAScript Language Specification: Well-Known Symbols; MDN: Symbol.iterator

One object, both roles

A generator object plays two parts at once. The standard says it conforms to both the iterator interface and the iterable interface, and MDN says the same: it has a next method, and for...of can also walk it. That is why a generator method can serve as an object's Symbol.iterator, and why a generator, once walked to the end, gives nothing more.

Why it fits here: It answers this topic's question: the generator a generator method returns is both the iterator and the iterable that for...of needs.

Sources: ECMAScript Language Specification: Generator Objects; MDN: Generator

In one line

An object joins the iteration protocol with a method under Symbol.iterator that returns an iterator, usually written as a generator method, *[Symbol.iterator](). yield* passes on another iterable's values, and each walk starts afresh.

Where it is used

These ideas are in nearly every program that handles lists or text. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
functions that return functionssettings remembered once, used many timesa discount(20) for the festival; a once() around a payment
chains of array methodsreports and totals from liststhe money taken on orders of more than one plate
localeCompare and Intl.Collatorevery list of names shown to peoplea class list in alphabet order, Hindi names included
regular expressionschecking and cleaning what people typea PIN code, a phone number, a vehicle number
the iteration protocolfor...of, spread and Array.from on any valuewalking a string, a Set or a Map
generators and iterablesvalues made one at a time, or without endticket numbers; a long log read line by line

Mistakes and debugging

These are the slips that people meet most often with this lesson's ideas. Every output below is the real one, from the code shown.

1. map with a function that takes more than you think

console.log(["1", "2", "3"].map(parseInt), ["1", "2", "3"].map(Number));
[ 1, NaN, NaN ] [ 1, 2, 3 ]

No error: map passes each item and its index, and parseInt reads its second argument as the number base. So it was called parseInt("2", 1) and parseInt("3", 2), which make no sense. The fix: map(Number), or map((s) => parseInt(s, 10)).

2. Numbers sorted as text

console.log([100, 25, 3].toSorted());
[ 100, 25, 3 ]

No error: 1 comes before 2 and 3 as a character. The fix: toSorted((a, b) => a - b).

3. A pattern without its ends

console.log(/\d{6}/.test("41100123"), /^\d{6}$/.test("41100123"));
true false

No error: the first pattern found six digits inside eight. The fix: ^ and $ when the whole text must match.

4. replace with fixed text, expecting every match

console.log("1,25,000".replace(",", ""));
125,000

No error: only the first comma went. The fix: replace(/,/g, "") or replaceAll(",", "").

5. A generator walked twice

function* abc() {
  yield "a";
  yield "b";
}
const g = abc();
console.log([...g], [...g]);
[ 'a', 'b' ] []

No error: the generator was used up by the first spread. The fix: call abc() again, or keep the values in an array.

6. for...of over a plain object

const stock = { tea: 4, dal: 2 };
for (const item of stock) console.log(item);
Uncaught TypeError: stock is not iterable
    at line 2

The fix: for (const [item, count] of Object.entries(stock)).

The debugging corner: break the chain

When a chain of methods gives a wrong answer, cut it into steps with a const for each, and print each one. The first step whose output surprises you holds the bug. For a pattern, test it on a list of good and bad examples at once, ["411001", "4110"].map((t) => pin.test(t)), before using it.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code

// functions that take and give functions
const discount = (percent) => (price) => price - (price * percent) / 100;
console.log(discount(20)(500));

// a chain, read as a sentence; names sorted with localeCompare
const orders = [{ who: "ravi", qty: 2 }, { who: "Asha", qty: 1 }, { who: "Kabir", qty: 3 }];
console.log(orders.filter((o) => o.qty > 1).map((o) => o.who).toSorted((a, b) => a.localeCompare(b)));

// patterns: test, and replace with a function
console.log(/^\d{6}$/.test("411001"), "Tea 15".replace(/\d+/g, (n) => `₹${n * 2}`));

// the protocol: Symbol.iterator gives an iterator; next gives { value, done }
const it = "ab"[Symbol.iterator]();
console.log(it.next(), [...it]);

// a generator method makes a class iterable
class Range {
  constructor(from, to) {
    this.from = from;
    this.to = to;
  }
  *[Symbol.iterator]() {
    for (let n = this.from; n <= this.to; n++) yield n;
  }
}
console.log([...new Range(1, 4)]);
400
[ 'Kabir', 'ravi' ]
true Tea ₹30
{ value: 'a', done: false } [ 'b' ]
[ 1, 2, 3, 4 ]
When you seeIt meansLook at
[ 1, NaN, NaN ] from map(parseInt)map passed the index as a second argumentmap(Number)
numbers in a strange ordera sort with no compare function(a, b) => a - b
capitals first, accents lastnames sorted by character codeslocaleCompare
a pattern that accepts bad textno ^ and $anchor both ends
TypeError: ... is not iterablefor...of or spread over a plain objectObject.entries, or a Symbol.iterator method
an empty second walka used-up iterator or generatora fresh one, or an array

The story: The log reads itself

You hand the work to functions that take functions. One keeps the north bell's lines, one turns each line into its strokes, and one adds them up. The names are sorted by the city's own rules for words, so that capitals and small letters sit together. For tomorrow's log, too long to hold at once, you write a generator that hands out one line at a time.

The morning's work now takes a moment, and asha sits where the alphabet says, between Arjun and Kabir.

Master Verge watches the count come out right three times running. "Say what you want," he says, "not how to walk there."

Reagents gathered: higher-order function, localeCompare, regular expression, iterator, generator, Symbol.iterator.

Sources