252

In this page I found a new JavaScript function type:

// NOTE: "function*" is not supported yet in Firefox.
// Remove the asterisk in order for this code to work in Firefox 13 

function* fibonacci() { // !!! this is the interesting line !!!
    let [prev, curr] = [0, 1];
    for (;;) {
        [prev, curr] = [curr, prev + curr];
        yield curr;
    }
}

I already know what yield, let and [?,?]=[?,?] do, but have no idea what the function* is meant to be. What is it?

P.S. don't bother trying Google, it's impossible to search for expressions with asterisks (they're used as placeholders).

thefourtheye
  • 206,604
  • 43
  • 412
  • 459
string QNA
  • 2,910
  • 3
  • 15
  • 13
  • 4
    The comment in the example is quite old now, `function*` syntax is supported in Firefox since v26: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function* . Older versions used a different syntax. – Nickolay Sep 09 '14 at 22:16
  • 40
    Regarding Google, just search for "function star" or "function asterisk". That's how I found this question ;). – trysis Feb 02 '15 at 22:05
  • 2
    Looks like the `*` was stripped from the link from @Nickolay. Here's a link [directly to `function*` at MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*). Sure enough, "basic" support [since v26](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*#Browser_compatibility). – ruffin Apr 29 '15 at 17:16
  • Another MDN link _(which, by the way, I found on the MDN page linked by OP)_: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator – BlueRaja - Danny Pflughoeft Dec 01 '15 at 17:20
  • Another useful MDN link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function* – Logan Jun 23 '17 at 05:46
  • On the note of searching for this question, there's a search engine called symbolhound that includes special characters in your searches – Eats Indigo Jun 07 '18 at 09:59
  • Check [this gist](https://gist.github.com/eyecatchup/4094d7b2a69cc55dd9958ff5da706bf8) out, it should explain it. – mekb Jul 23 '19 at 10:08

3 Answers3

207

It's a Generator function.

Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.

Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. When the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function.


Historical note:

It's a proposed syntax for EcmaScript.next.

Dave Herman of Mozilla gave a talk about EcmaScript.next. At 30:15 he talks about generators.

Earlier, he explains how Mozilla is experimentally implementing proposed language changes to help steer the committee. Dave works closely with Brendan Eich, Mozilla's CTO (I think), and the original JavaScript designer.

You can find more detail on the EcmaScript working group wiki: http://wiki.ecmascript.org/doku.php?id=harmony:generators

The working group (TC-39) has general agreement that EcmaScript.next should have some kind of generator iterator proposal, but this is not final.

You shouldn't rely on this showing up without changes in the next version of the language, and even if it doesn't change, it probably won't show up widely in other browsers for a while.

Overview

First-class coroutines, represented as objects encapsulating suspended execution contexts (i.e., function activations). Prior art: Python, Icon, Lua, Scheme, Smalltalk.

Examples

The “infinite” sequence of Fibonacci numbers (notwithstanding behavior around 253):

function* fibonacci() {
    let [prev, curr] = [0, 1];
    for (;;) {
        [prev, curr] = [curr, prev + curr];
        yield curr;
    }
}

Generators can be iterated over in loops:

for (n of fibonacci()) {
    // truncate the sequence at 1000
    if (n > 1000)
        break;
    print(n);
}

Generators are iterators:

let seq = fibonacci();
print(seq.next()); // 1
print(seq.next()); // 2
print(seq.next()); // 3
print(seq.next()); // 5
print(seq.next()); // 8
Community
  • 1
  • 1
Mike Samuel
  • 109,453
  • 27
  • 204
  • 234
  • 7
    Follow up: what does a for loop with no parameters (`for(;;)`) do? Why use it in this context? – Fergie Aug 28 '13 at 07:22
  • 13
    @Fergie, `for(;;)` is the same as `while (true)`. It's used in this context since the Fibonacci sequence is an unbounded sequence. – Mike Samuel Aug 28 '13 at 07:37
  • 3
    @DaveVandenEynde, prior prior art: Python yield. Prior prior prior art: CLU and Icon. – Mike Samuel Dec 19 '14 at 17:06
52

It's a generator function - and it said so in the page you cite, in the comment you replaced with "this is the interesting line"...

Basically it's a way to specify sequences programmatically so that they can be passed around and elements accessed by index without having to compute the entire sequence (possibly infinite in size) beforehand.

Michael Borgwardt
  • 327,225
  • 74
  • 458
  • 699
  • 10
    "accessed by index without having to compute the entire sequence" is possibly the most helpful bit of explanation about generators I've come across so far. I could see using this in an app, vs previously just understanding it theoretically. – wes Aug 06 '15 at 16:17
11

The function* type looks like it acts as a generator function for processes that can be iterated. C# has a feature like this using "yield return" see 1 and see 2

Essentially this returns each value one by one to whatever is iterating this function, which is why their use case shows it in a foreach style loop.

Community
  • 1
  • 1
invalidsyntax
  • 640
  • 1
  • 5
  • 14