ES6 Generators Are Nothing Magical

Have you ever seen before and after makeup pics?

Source: Vadim Andreev

The difference is often so startling it may be hard to tell they are the same person at first glance!

The truth is that even the most dramatic changes are still the same person. The appearance may have changed, makeup tricks may have altered the perception of their facial structures and features but at the end of the day they’re still the same person.

ES6 Generators are no different.

Under everything, ES6 Generators are still a loop structure that allows you to determine if you want to go to the next iteration. In older loops you use break;  with generators you use generator.next() .

Today I stumbled on a post where Derick Bailey finds a use-case for generators while wrangling some data.

More recently, I rant in to a scenario where I have a hierarchical tree of JSON data and I needed to iterate through the attributes at the very bottom, selecting the parent object of the attribute that matched a specific criteria.

After thinking through a myriad of ways to handle this, my old generators post popped in to my head, and I wondered if I could use it.

His solution included a mish-mash of for loops, generators and a while loop thrown in the mix.

It’s not the first time I’ve seen him tackle a problem and wonder why his way looks so different from mine.

When I was demonstrating my thought process when Writing Reusable Javascript, the snippet created was a loop function with the ability to externally determine when it should stop.

I grabbed the function, the sample data Derick used and quickly threw it together a solution for the problem.

Solution on JSBIN (output is in the browser’s console)

Essentially the usecase for a generator he saw, yet every bit as clean. I’d argue mine’s cleaner but I’m biased.

My point?

Generators look prettier to some people but honestly they’re nothing magical. It’s still the same person with beautiful features, except with a little visual aid to help us focus on certain attributes and block out others.

Javascript is pretty and I really don’t need makeup / magic to appreciate it. For everyone else, there’s ES6.