5

In ECMAScript 6, there is a feature being implemented called "generators".

"Generators" seem to be functionally equivalent to "coroutines" from other programming languages. JavaScript even uses the same keywords like yield in these generators.

If they function the exact same, or at least have the same concept behind them, why are are they called "generators" in JavaScript and "coroutines" in others?

The only possible reason I can think of why this is, is because generators are functionally different, therefore they gave it a different name, but after review some code, I'm not so sure....

Here are two functions that use coroutines / generators in Python and JavaScript, just so you can compare.

(From Tasks and coroutines in the Python documentation)

import asyncio
import datetime

@asyncio.coroutine
def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        yield from asyncio.sleep(1)

loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

(From Iterators and generators in the MDN documentation)

function* idMaker(){
  var index = 0;
  while(true)
    yield index++;
}

var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

I'd like to add that my knowledge of programming doesn't go much outside of JavaScript.

I've stuck with JavaScript for 4+ years. Perhaps this is a gap in my knowledge, which is why I'm asking here.

  • https://en.wikipedia.org/wiki/Coroutine#Comparison_with_generators – Bergi Aug 07 '15 at 14:18
  • 1
    I think that language-agnostic duplicate answers your question well. If you've got further questions, or something is left unclear, or you think there's something specific to JS that you'd need an answer for, please comment. – Bergi Aug 07 '15 at 14:56
  • @Bergi, No, I think this is a duplicate. Mainly because my last statement. I wasn't away generators existed outside of JavaScript because I don't program elsewhere. –  Aug 07 '15 at 22:50
  • Most programming concepts you will find in JS are in fact older than you and me (and older than JS) :-) – Bergi Aug 08 '15 at 16:22

0 Answers0