Frontend Development: Generator

Peter Jeon·2023년 7월 4일
0

Frontend Development

목록 보기
38/80
post-custom-banner

In JavaScript, a generator is a special kind of function that can be paused and resumed, allowing it to generate a sequence of results over time, rather than computing them all at once and returning them in a huge array. This brings efficiency especially when dealing with large data sets.

Generator vs Regular Functions

AspectGenerator FunctionsRegular Functions
PausingCan pause and resume executionCannot pause execution once started
ResultYields multiple sequential resultsReturns a single result
SymbolFunction*function

How to Create a Generator

Generators are defined using a special syntax that involves the function keyword followed by an asterisk, function*:

function* idMaker() {
  let id = 0;
  while (true) {
    yield id++;
  }
}

In the code above, idMaker is a generator function that generates an endless series of IDs.

How to Use a Generator
Here's how you can use the idMaker generator:

let gen = idMaker(); // "gen" is a generator object

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

Every time we call gen.next(), we get the next ID from the idMaker generator. The value property gives us the value that was yielded by the yield expression inside the generator.

Conclusion

In conclusion, generators are a powerful feature in JavaScript that allow you to write functions that can be paused and resumed, yielding multiple results over time. They can make your code cleaner and easier to read, especially when dealing with asynchronous code or complex control flows. Understanding how to use generators effectively can greatly enhance your capability as a JavaScript developer.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글