Skip to content
Related Articles

Related Articles

JavaScript | function* expression
  • Last Updated : 02 Jun, 2020

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




<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>

Output:

123 - Geeks

Example 2:

Javascript




<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>

Output:

 1
 4
 9
 16
 25

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

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge
My Personal Notes arrow_drop_up
Recommended Articles
Page :