JavaScript Example (Program)
Learn Details

Generator Function


generator function एक function है जिसका use function के किसी ख़ास statement को print या return करने के लिए किया जाता है

Q. How to work generator function ?

किसी function के आगे * का sign देने से वह generator function बन जाता है। इसके statement को रोकने के लिए "yield" keyword का उसे किया जाता है

Note :- generator को access करने के लिए next() method का use किया जाता है

Syntax 1: for create Generator function:

function *function_name (){
// }

Break Steatement of Generator function

function *function_name (){
yield // your statement here
yield // your statement here
yield // your statement here
yield // your statement here
}

Note :- "yield" keyword, generator function statement को रोकने काम करता है।


Syntax 2: for access Generator Value

Generator_Name.next().value

Example 1 : Create a Generator



<script>     
    function *Student (){
        yield "Roll 1";
        yield "Roll 2";
        yield "Roll 3";
        yield "Roll 4";
        yield "Roll 5";
      }
    let x =   Student();
      x.next()
      x.next()
    console.log(x.next().value)
</script>
 

Example 2 : Access Generator value by loop



<script>     
function *Student (){
      yield "Roll 1";
      yield "Roll 2";
      yield "Roll 3";
      yield "Roll 4";
      yield "Roll 5";
      yield "Roll 6";
    }
  let x =   Student();
   for(y of x){
        console.log(y)  
   }
</script>
 

Example 3 : Create Generator with loop



<script>     
  function *Student (){
        let num = 200;
        while(true){
            yield num += 10;
        }
    }
  let x =   Student();
    console.log(x.next())
    console.log(x.next())
    console.log(x.next())
</script>
 

Example 4 : Create Generator using string and array



<script>     
  function *Student (){
        yield "Hello";
        yield ["Ram", "Shyam", "Suresh"]
      }
  let x =   Student();
  console.log(x.next())
  console.log(x.next())
</script>
 

Example 5 : Access Generator Array Value



<script>     
  function *Student (){
          yield *["Ram", "Shyam", "Suresh"]
        }
    let x =   Student();
    console.log(x.next())
    console.log(x.next())
</script>
 

Example 6 : Create Generator with user value (Generator with return value)



<script>     
    function *Student (){
      let myvalue = yield;
      console.log(myvalue)
    }
    let x =   Student();
    x.next();
    x.next("Javascript")
</script>
 

Example 7 : Access Generator value with spread operator



<script>     
  function *Student (){
    yield *["Ram", "suresh", "Gagan"]
  }
  let x = Student();
 console.log(x.next())
 //console.log(x.next())
 console.log([...x])
</script>