Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does star (*) mean in JavaScript function definition in Koa framework? [duplicate]

I have been familiarising myself with Koa (http://koajs.com/). Many of the examples include star character in place of function name. For instance in the hello world example there is:

var koa = require('koa');
var app = koa();

app.use(function *(){
  this.body = 'Hello World';
});

app.listen(3000);

What does this star mean?

like image 795
jsalonen Avatar asked May 02 '14 07:05

jsalonen


People also ask

What does the star * do in JavaScript?

The function* declaration ( function keyword followed by an asterisk) defines a generator function, which returns a Generator object.

What is use of in JS?

The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists. Anatomy of a simple JavaScript object.


1 Answers

It generally creates an "iterator" so you can yield result's one at a time.
Similar to C#'s yield key work.

Official Information

Example

The “infinite” sequence of Fibonacci numbers (notwithstanding behavior around 2^53):

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
like image 101
Amir Popovich Avatar answered Sep 19 '22 16:09

Amir Popovich