Перейти к основному содержимому
← ⚡ JavaScript & the browser·Модуль C6 · Урок 4
ЗаданиеWrite function* fizz() that yields the strings 'fizz','buzz','fizzbuzz' (in that order). Use for-of to log each. Then write function* range(from, to) and log [...range(5, 8)].join(',') — should print 5,6,7,8.

Generators: function* and yield

150 XP9 min
Теория

What a generator gives you

A function* (note the asterisk) returns a generator — an object that's BOTH an iterator AND iterable. Each yield produces the next value; execution pauses there and resumes on the next .next() call.

function* range(from, to) {
  for (let n = from; n <= to; n++) yield n;
}

for (const n of range(1, 3)) console.log(n); // 1, 2, 3
[...range(1, 3)];                             // [1, 2, 3]

Same result as the Symbol.iterator object in C6-03 — five lines instead of fifteen.

Yielding sequences

yield can be called any number of times, in any pattern:

function* greet() {
  yield "hi";
  yield "there";
  yield "friend";
}

Each yield is a checkpoint. The generator's runtime saves the function's local state between calls — that's why you can have an explicit for loop with yield inside it.

return inside a generator

return value finishes the generator immediately. Subsequent .next() calls return { value: undefined, done: true }.

🔒

Зарегистрируйся чтобы кодить

Теория открыта всем. Интерактивный редактор, живой превью и проверка открываются с 7-дневным бесплатным trial — нужна карта, отмена в любое время.

Регистрация — бесплатный trial →

Первые 10 уроков в каждом треке — бесплатные. Карта не нужна.

← НазадСледующий урок →

Получай один совет по Python или веб-разработке — каждый день в почте

Коротко, без воды, без спама. Отписаться — в один клик.