JavaScript yield* expression

The yield* expression in JavaScript is used when one wants to delegate some other iterable object. This function iterate over the particular operand and yields each value that is returned by it.

Syntax:

yield* expression;

Return Value: It returns the iterable object.

Example 1:

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" 
        content="width=device-width, initial-scale=1.0">
  <title>JavaScript yield* expression</title>
</head>
<body>
  <script>
    function* func1() {
      yield "a";
      yield "b";
      yield* func3();
    }
    function* func3() {
      yield "geeks";
    }
    function* func2() {
      yield* func1();
      yield 4/2;
      yield 5/2;
    }
    const it = func2();
    console.log(it.next()); 
    console.log(it.next()); 
    console.log(it.next()); 
    console.log(it.next()); 
    console.log(it.next()); 
    console.log(it.next()); 
  </script>
</body>
</html>

chevron_right


Output:



Example 2: Using other iterable objects with yield* in JavaScript.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" 
        content="width=device-width, initial-scale=1.0">
  <title>JavaScript yield* expression</title>
</head>
<body>
  <script>
    function* func1() {
      yield* func3(1, 2, 3, 4);
    }
    function* func3(){
      yield * Array.from(arguments);
    }
    function* func2(){  
      yield* func1();
      yield* ["from array", "from array"];
    }
    const it = func2();
    console.log(it.next()); 
    console.log(it.next()); 
    console.log(it.next()); 
    console.log(it.next()); 
    console.log(it.next()); 
    console.log(it.next()); 
  </script>
</body>
</html>

chevron_right


Output:

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

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.