The yield Keyword in JavaScript

The yield Keyword in JavaScript

This article will discuss using the yield keyword in the generator function and the purpose. With an example of JavaScript, we will execute the functionality and usage of the yield keyword.

Use the yield Keyword in JavaScript

In JavaScript, we can’t use yield expressions in callbacks or nested functions. We use the yield keyword to pause and resume the generator functions asynchronously.

The yield statement returns an object containing two properties, value and done.

  1. value: This property contains an actual value passed to the generator function.

  2. done: This property contains a Boolean value. When a generator function is fully completed, it will return true; otherwise, false.

  3. Generator function: To convert a function into a generator, we need to add the asterisk symbol (*) with the function keyword. In JavaScript, the generator function is similar to the normal function.

    We use the yield keyword to return any value. If we want to pause the execution of the generator function, we need to use the yield expression.

    If we want to resume the execution again, then we must require to call the next() method. The function keeps executing until it finds the yield or return statement.

    When the generator function is called again, implementation will continue from the last yield expression.

Here, we will create an example to generate a function and use the yield keyword to pause the execution.

Example code:

<script>

function* testGenerator(i) {
    while (i < 5) {
        yield i++;
    }

}

//creating an object with our function testGenerator

const test = testGenerator(2);

//return object with 2 value is passed to the testGenerator yield expression

console.log(test.next());

//return object with 3 value.

console.log(test.next());

//return object with 4 value

console.log(test.next());

</script>

Output:

            [object Object] {
            done: false,
            value: 2

            }

            [object Object] {
            done: false,
            value: 3
            }

            [object Object] {
            done: false,
            value: 4
            }

We have declared the generator function testGenerator() with an asterisk symbol (*) in the above JavaScript source code. We have used a while loop to pause the execution with the yield keyword inside the function.

Then, we created an object test with our generator function and passed the value 2. In console.log, we called the function object test and the next() method.

You can see the returned objects and execution flow in the log box of the compiler.

Related Article - JavaScript Keyword