JavaScript | function* expression

The function* is an inbuilt keyword in JavaScript which is used to define a generator function inside an expression.

Syntax:

function* [name]([param1[, param2[, ..., paramN]]]) {
   statements
}

Parameters: This function accepts the following parameter as mentioned above and described below:

  • name: This parameter is the function name.
  • paramN: This parameter is the name of an argument to be passed to the function.
  • statements: These parameters are comprise the body of the function.

Below examples illustrate the function* expression in JavaScript:

Example 1:



Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    // Illustration of function* expression
    // use of function* keyword
    function* func() {
      yield 1;
      yield 2;
      yield 3;
      yield " - Geeks";
    }
      
    let obj = '';
      
    // Function calling
    for (const i of func()) {
          obj = obj + i;
    }
  
    // Output
    console.log(obj);
</script>

chevron_right


Output:

123 - Geeks

Example 2:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    // Illustration of function* expression
    // use of function* keyword
    function* func2(y){
       yield  y * y;
    };
  
    function* func1(){
      for (let i = 1; i < 6; i++)
      {
        yield* func2(i);
      }
    };
  
    // Function calling
    for (const x of func1()) {
    
      // Output
      console.log(x);
    }
</script>

chevron_right


Output:

 1
 4
 9
 16
 25

Supported Browsers: The browsers supported by JavaScript function* expression are listed below:

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.