Yield
A keyword in JavaScript generator functions that pauses function execution and returns a value, allowing the function to be resumed later.
Overview
The yield keyword is used in generator functions to pause execution and return a value to the caller. Unlike regular functions that run to completion, generators can yield multiple values over time, one at a time. This makes generators useful for implementing iterators, managing asynchronous flows, and working with infinite sequences.
Example
javascript// Basic generator function 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 } // Using for...of loop for (const num of countUp()) { console.log(num); // 1, 2, 3 } // Generator with parameters function* multiply(x) { yield x * 1; yield x * 2; yield x * 3; } const gen = multiply(5); console.log(gen.next().value); // 5 console.log(gen.next().value); // 10 console.log(gen.next().value); // 15 // Infinite sequence function* fibonacci() { let [prev, curr] = [0, 1]; while (true) { yield curr; [prev, curr] = [curr, prev + curr]; } } const fib = fibonacci(); console.log(fib.next().value); // 1 console.log(fib.next().value); // 1 console.log(fib.next().value); // 2 console.log(fib.next().value); // 3 console.log(fib.next().value); // 5 // yield* (delegate to another generator) function* gen1() { yield 1; yield 2; } function* gen2() { yield* gen1(); yield 3; } console.log([...gen2()]); // [1, 2, 3] // Practical example: ID generator function* idGenerator() { let id = 1; while (true) { yield id++; } } const getId = idGenerator(); console.log(getId.next().value); // 1 console.log(getId.next().value); // 2 console.log(getId.next().value); // 3 // Two-way communication function* chat() { const response = yield 'Hello!'; yield `You said: ${response}`; } const conversation = chat(); console.log(conversation.next().value); // 'Hello!' console.log(conversation.next('Hi').value); // 'You said: Hi'
Key Points
- Used in generator functions (function*)
- Pauses execution and returns a value
- Function can be resumed with .next()
- Enables lazy evaluation
- Useful for iterators and async patterns
Learn More
- Asynchronous - Async programming
- Promise - Promises
- Async/Await - Async syntax
- MDN: yield