Menu

Generators in JavaScript: Functions That Can Pause
πŸ“°

Generators in JavaScript: Functions That Can Pause

DEV Community: frontendΒ·Arhan KhanΒ·1 day ago
#JlV6uBZh
#devtofrontend#devto#dev#next#value
Long article (347 words) β€” no AI summary yet.
Reading 0:00
15s threshold

A normal function runs from start to finish in one go. A generator function can pause in the middle, hand a value back, and resume later exactly where it stopped. That makes it perfect for producing values one at a time β€” without building a giant array first.

You write a generator with function* and pause it with yield :

function * countUp ( ) { yield 1 ; yield 2 ; yield 3 ; }

const counter = countUp ( ) ; console . log ( counter . next ( ) ) ; // { value: 1, done: false } console . log ( counter . next ( ) ) ; // { value: 2, done: false } console . log ( counter . next ( ) ) ; // { value: 3, done: false } console . log ( counter . next ( ) ) ; // { value: undefined, done: true }

Enter fullscreen mode

Exit fullscreen mode

Each call to next() runs the function until the next yield , then pauses again. The returned object tells you the value and whether the generator is finished.

Generators are most useful when the sequence is long or infinite.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.