This lesson is only accessible in the paid version of the course.
Get access to all lessons 💫 price: 34.99$
Do you speak JavaScript?
In this video, we will discuss generators in JavaScript and how they allow you to create custom iterable objects. We will explore the `yield` keyword and how it is used to pause and resume the execution of a generator function.
A generator is a special type of function in JavaScript that can be paused and resumed later. It is defined using the function*
keyword instead of function
. Generators are useful in situations where you need to iterate over a large or infinite collection of items, or when you need to perform a long-running computation that you don't want to block the execution of your program.
When a generator is called, it returns an iterator object. The iterator object has a next()
method that can be called to execute the next line of the generator function. Each time the generator function encounters a yield
expression, it returns the value of the expression and suspends its execution. The generator can later be resumed by calling the next()
method again.
function* generator() {
yield 1;
yield 2;
yield 3;
}
const myGenerator = generator();
console.log(myGenerator.next().value); // 1
console.log(myGenerator.next().value); // 2
console.log(myGenerator.next().value); // 3
In this example, the generator function generator
yields the values 1, 2 and 3 one by one. Each time the next()
method is called on the generator object, the generator resumes its execution and returns the next value.
Generators are also useful in combination with other language features such as for-of loops or destructuring.
function* generator() {
yield 1;
yield 2;
yield 3;
}
for (let value of generator()) {
console.log(value);
}
// Output: 1 2 3
Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.
Materials related to the lesson:
→ Files associated with the lesson