DEV Community

loading...
Cover image for Quick Tip about function vs function*

Quick Tip about function vs function*

Benjamin🦸‍♂️Auzanneau™
Developer / Front-end enthusiast / JavaScript Hero / Podcaster 🏀🏒🍻🇨🇦🐿️🇫🇷🦸‍♂️🎙️🎧
・1 min read

What is function * ?

It's generator function which returns a Generator object.
Generators are intricately linked with iterators.

But what is a generator function ?

It's a function that can stop midway and then continue from where it stopped !

function * generatorExample() {
  let counter = 0;
  yield `First step ! ${counter}`;
  counter++;
  yield `Second step ! ${counter}`;
  counter++;
  console.log('No yield, the function is done');
}

const generator = generatorExample();
console.log(generator.next().value); // First step ! 1
console.log(generator.next().value); // Second step ! 2
console.log(generator.next().value); // No yield, the function is done
Enter fullscreen mode Exit fullscreen mode

The Generator object offers a next() function that you can call to go further into the next step of the generator.

You can check MDN for more information.

That's it, make good use of it !


I'm not a native English speaker so, thanks in advance if you want to improve my article with correct syntax/grammar/sentences.

I can accept all kind remarks :)

Cover by Wolfgang Rottmann on Unsplash

Discussion (0)