What is Generator function in javascript?

JavaScript Generators

Generator function OR iterators we define from the astrisk(*) symbol with function keywords.

   // syntax
function* generator() {
    console.log('This is first value');
    yield 1;
    console.log('This is second value');
    yield 2;
}

first point for the astrisk(*) means this is generator and then "yield" means return value and pause the function execution. need to use .next().value for the value and use for the .done run will be untill getting true, when true will be finished find false then execution will be finished.

<script>
function* sheo(i) {
  yield i;
  yield i + 10;
}

const mainS = sheo(50);

console.log(mainS.next().value);
// 50

console.log(mainS.next().value);
// 60
    </script>

And another Example for the Generator function.

<script>
        function* getFunction(data) {
          yield 'this is total num' + data;
          yield 'this is double num' + data * 2;
          yield 'this is half' + data / 2;
          yield 'this is multiple' + data * data;
        }

        const myNum = getFunction(10);
        console.log(myNum.next())
        console.log(myNum.next().value);
        console.log(myNum.next().value);
        console.log(myNum.next().value);
        console.log(myNum.next().value);
        console.log(myNum.next().done);
    </script>


No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.