QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads JavaScript “yield” Keyword and “function*()” Syntax

JavaScript “yield” Keyword and “function*()” Syntax

This post is a part 10 of ECMAScript 6 Complete Tutorial post series.

ECMAScript 6 specification introduced a new JavaScript feature called as JavaScript Generators. JavaScript’s yield keyword and function*() syntax together make JS Generators.

In nutshell JavaScript generators provide a new way for functions to return a collection and also a new way of looping(or iterating) through the elements of the returned collection.

Earlier to JavaScript Generators you would do something like this

function collection_name()
{
    return [1, 3, 5, 7];
}

var collection = collection_name();

for(var iii = 0; iii < collection.length; iii++)
{
    console.log(collection[iii]);
}

Here is how you can do the same using Generators

function* collection_name()
{
    yield 1;
    yield 3;
    yield 5;
    yield 7;
}

for(var iii  of collection_name())
{
    console.log(iii);
}

Internally JavaScript creates a object with Symbol.iterator property from the yielded values which is what for of construct needs for iterating a collection.

Feb 18, 2015Narayan Prusty
"foreach" vs "for of" vs "for in" in JavaScriptTrack Adblock Users with Google Analytics
Comments: 2
  1. Michu
    7 years ago

    One more thing worth mentioning is that yield can also be called with an asterisk, like this:

    yield* [1, 2, 3, 4, 5];

    This means the same thing as:

    yield 1;
    yield 2;
    yield 3;
    yield 4;
    yield 5;

    ReplyCancel
    • plankton
      6 years ago

      wow, that was nice. thanks to the author above n also @michu.

      ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

8 years ago 2 Comments Web Development
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
Related Articles
  • Default Function Arguments Values in JavaScript
  • JavaScript “for of” Loop Tutorial
  • JavaScript “Set” Object
  • JavaScript “class” Keyword
  • CSS3 :before and :after Psuedo-Elements and Generated Content
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license