MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Generators with function*0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
12.1Understanding Iterators12.2Creating Custom Iterators12.3Generators with function*
HomeTutorialsJavaScript for IntermediateGenerators with function*
Using console methods

Generators with function*

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

While custom iterators are powerful, manually managing state variables and returning { value, done } boilerplate can be tedious. Generators—defined using the function* syntax and the yield operator—provide a clean, stateful way to define iterative algorithms.


1. Syntax & Core Mechanics

A generator function returns a Generator object, which conforms to both the Iterable and Iterator protocols simultaneously:

1function* numberSequence() {
2 console.log('Sequence started');
3 yield 1;
4 console.log('Resumed after 1');
5 yield 2;
6 console.log('Resumed after 2');
7 yield 3;
8 console.log('Sequence finished');
9}
10 
11// Calling the generator does NOT execute code immediately!
12// It returns a Generator Iterator:
13const gen = numberSequence();
14 
15console.log(gen.next()); // Prints: 'Sequence started', Returns: { value: 1, done: false }
16console.log(gen.next()); // Prints: 'Resumed after 1', Returns: { value: 2, done: false }
17console.log(gen.next()); // Prints: 'Resumed after 2', Returns: { value: 3, done: false }
18console.log(gen.next()); // Prints: 'Sequence finished', Returns: { value: undefined, done: true }

2. Infinite Generators & Lazy Evaluation

Because generators pause until next() is explicitly called, they can represent infinite sequences without consuming infinite memory (Lazy Evaluation):

1function* idGenerator() {
2 let id = 1000;
3 while (true) {
4 yield `UID_${id++}`;
5 }
6}
7 
8const ids = idGenerator();
9 
10console.log(ids.next().value); // 'UID_1000'
11console.log(ids.next().value); // 'UID_1001'
12console.log(ids.next().value); // 'UID_1002'
13// Memory footprint remains constant!

3. Two-Way Communication: Passing Values into next(value)

The yield keyword is not only an output statement—it can also receive inputs passed to gen.next(arg):

1function* conversation() {
2 const name = yield 'What is your name?';
3 const role = yield `Nice to meet you, ${name}! What is your role?`;
4 return `Registered ${name} as ${role}.`;
5}
6 
7const chat = conversation();
8 
9console.log(chat.next().value); // 'What is your name?'
10console.log(chat.next('Priya').value); // 'Nice to meet you, Priya! What is your role?'
11console.log(chat.next('Architect').value); // 'Registered Priya as Architect.'

4. Delegating Generators with yield*

The yield* operator delegates iteration to another generator or iterable:

1function* frontendTech() {
2 yield 'HTML';
3 yield 'CSS';
4 yield 'JavaScript';
5}
6 
7function* backendTech() {
8 yield 'Node.js';
9 yield 'Django';
10}
11 
12function* fullStackCurriculum() {
13 yield* frontendTech(); // Delegates to frontendTech generator
14 yield* backendTech(); // Delegates to backendTech generator
15 yield 'Docker';
16}
17 
18console.log([...fullStackCurriculum()]);
19// ['HTML', 'CSS', 'JavaScript', 'Node.js', 'Django', 'Docker']

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
How do you declare a generator function in JavaScript?
Question 2
What happens when you invoke a generator function (e.g. const g = myGen())?
Question 3
What is the role of the yield keyword inside a generator?
Question 4
What does the yield* operator do?
Question 5
Can an infinite while (true) loop inside a generator crash the browser with an Out of Memory error?
Next Lesson

Using console methods

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Creating Custom IteratorsUsing console methods

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext