As we know JavaScript is a lightweight programming language in which generators were introduced in ECMAScript 2015. A generator is a process that has many output values and may be stopped and started. In JavaScript, a generator is made up of a generator function that produces an iterable Generator object.
Introduction to Generators in JavaScript
The generator’s function is as same as the regular function but there is a bit of difference in that the generator function can be resumed and paused. In JavaScript generally, functions are not stope when once they are invoked. Usually, the concept of generators is seen in asynchronous programming.
Syntax of Generator function in JavaScript
Now we will be going to discuss the syntax of the generator function in the JavaScript and also compare it with the regular function.
The function * syntax is used to build generator functions, and the yield keyword is used to pause them.
function * genFunc() {
yield 'Hello';
yield 'World';
}
const g = genFunc(); // g is a generator
g.next(); // { value: 'Hello', done: false }
g.next(); // { value: 'World', done: false }
g.next(); // { value: undefined, done: true }
…
When a generator function is first called, none of its code is run, Instead, a generator object is returned. Values are consumed by invoking the next() method of the generator, which runs code until it comes across the yield keyword, at which point it pauses and waits until the next() is invoked once more.
In the above code, after our final statement, continually calling g.next() will only produce the same return object: {value: undefined, done: true} because we have not defined anything after the ‘world’ in our genFunc() function.
The yield keyword pauses the generator function’s execution and gives the caller of the generator the value of the expression that follows it. It is comparable to the generator-based version of the return keyword. It can only be directly called from the generator function that contains yield.
Comparison with regular function
function regFunc() {
console.log("Hello World");
}
// Hello World
In the regular function, we do not use the ‘*’ function as you can see above example it also does not use the yield function. As we discussed above that the main difference between the regular function and the generator function is that the generator function can be stopped and paused. So by the above example, you can see that we don’t have the choice to stop it and directly print the whole statement together i.e “Hello world”.
Conclusion
In the article, we have learned that the generator’s function is as same as the regular function but there is a bit of difference in that the generator function can be resumed and paused. In JavaScript generally, functions are not stope when once they are invoked. Usually, the concept of generators is seen in asynchronous programming.