Have you ever heard of the intriguing “yield” keyword in JavaScript?
And you are curious to know its purpose and how yield keyword works in JS.
Do you want to know this keyword? So, keep on reading!
To learn about the yield keyword in JavaScript, which is a powerful tool used to pause and resume generator functions.
What is yield in JavaScript?
The yield keyword in JavaScript is used to pause and resume a generator function.
A generator function is a special type of function that can be paused and resumed, allowing it to produce a sequence of values over time.
When you call a generator function, it returns an iterator object that you can use to iterate over the sequence of values produced by the generator.
Syntax
yield expression; ✅
Parameter
📌 expression (optional)
The value that the generator function gives out using the iterator rule. If you don’t specify anything, it will give out undefined.
Return value
The yield function returns a value you can use with the generator’s next() method to start running once more.
How does yield keyword works in JavaScript?
The yield keyword is used to pause the execution of the generator function and return the value of the expression following the yield keyword to the generator’s caller.
It’s like a generator-based version of the return keyword. After the generator is paused on a yield expression, its code execution remains paused until you call again the generator’s next() method.
When you pass an optional value to the generator’s next() method, that value becomes the value returned by the generator’s current yield operation.
In simple words, the yield keyword is used in JavaScript to pause and resume a generator function, allowing it to produce a sequence of values over time.
How to use yield keyword?
Here’s a step-by-step guide on how to use the yield keyword in a generator function in JavaScript:
Step 1:
You have to define first a generator function using the function* syntax.
For example:
function* sampleGenerator() {
// …
}
Step 2:
Inside the generator function, use the yield keyword to pause the execution of the function and return a value to the generator’s caller.
For example:
function* sampleGenerator() {
yield 1;
yield 2;
yield 3;
}
Step 3:
Create an iterator object by calling the generator function and assign it to a variable.
For example:
const sampleIterator = sampleGenerator();
Step 4:
Use the next() method of the iterator object to iterate over the sequence of values produced by the generator.
Whenever you use the next() method, the generator continues running until it hits the next yield expression. Then it takes a break and gives you the value that comes after the yield keyword.
For example:
console.log(sampleIterator.next().value); // 1
console.log(sampleIterator.next().value); // 2
console.log(sampleIterator.next().value); // 3
Finally, we’re done! By executing these steps, you can use the yield keyword in a generator function to produce a sequence of values over time.
Here’s the complete code:
function* sampleGenerator() {
yield 10;
yield 20;
yield 30;
}
const sampleIterator = sampleGenerator();
console.log(sampleIterator.next().value);
console.log(sampleIterator.next().value);
console.log(sampleIterator.next().value);
Output:
10
20
30
Examples code using yield keyword
Generator Function with Parameters
function* idGenerator(start, end) {
for (let i = start; i <= end; i++) {
yield i;
}
}
const samplegen = idGenerator(1, 5);
console.log(samplegen.next().value);
console.log(samplegen.next().value);
console.log(samplegen.next().value);
console.log(samplegen.next().value);
console.log(samplegen.next().value);
We define a generator function that takes two parameters: start and end. The function employs a for loop to go through a sequence from start to end. It cleverly uses the yield keyword to take breaks and provide you with each value in that sequence.
Output:
1
2
3
4
5
Yielding from another Generator
function* numbers() {
yield 1;
yield* moreNumbers();
yield 6;
}
function* moreNumbers() {
yield 2;
yield 3;
yield 4;
yield 5;
}
const samplegen = numbers();
console.log(samplegen.next().value);
console.log(samplegen.next().value);
console.log(samplegen.next().value);
console.log(samplegen.next().value);
console.log(samplegen.next().value);
console.log(samplegen.next().value);
In our second example, we define two generator functions: numbers() and moreNumbers().
Inside the numbers() function, we use the yield* syntax to delegate to another generator function.
This allows us to pause execution of the first generator and resume execution of the second generator until it is complete.
Output:
1
2
3
4
5
6
What is the difference between return and yield in JavaScript?
The yield and return keywords are both used in JavaScript to return values from a function, but they work in different ways.
The return keyword is used to end the execution of a function and return a value to the caller.
Once a return statement is encountered, the function exits immediately and no further code is executed.
On the other hand, the yield keyword is used to pause and resume the execution of a generator function.
When a generator function encounters a yield statement, it returns the value of the expression following the yield keyword to the generator’s caller, but does not end the execution of the function.
Instead, it pauses execution at that point and remembers its state.
When you use the generator’s next() method again, it starts running again from where it stopped last time.
Here’s an example that demonstrates the difference between return and yield:
function* sampleGenerator() {
yield 10;
yield 20;
return 30;
}
const gen = sampleGenerator();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
As you can see in our example code, we define first a generator function called sampleGenerator that uses both the yield and return keywords.
When we call the generator’s next() method for the first time, it returns an object with a value property of 10 and a done property of false, indicating that there are more values to be returned.
The second call to next() returns an object with a value property of 20 and a done property of false.
The third call to next() returns an object with a value property of 30 and a done property of true, indicating that there are no more values to be returned.
Output:
{ value: 10, done: false }
{ value: 20, done: false }
{ value: 30, done: true }
Conclusion
In conclusion, the yield keyword in JavaScript is a powerful tool used within generator functions to pause and resume their execution.
It allows generator functions to produce a sequence of values over time.
When a generator function encounters the “yield” keyword, it temporarily suspends its execution and returns the value specified by the keyword to the caller.
It enables the generator function to maintain its state and continue execution from where it left off when the “next()” method is called again.
This feature is particularly useful when dealing with asynchronous or iterative operations.
In contrast, the “return” keyword ends the execution of a function and immediately returns a value to the caller.
We are hoping that this article provides you with enough information that helps you understand the yield in JavaScript.
If you want to dive into more JavaScript topics, check out the following articles:
Thank you for reading itsourcecoders 😊.