ES6 Generators and Iterators: a Developer’s Guide

ES6 brought a number of new features to the JavaScript language. Two of these features, generators and iterators, have substantially changed how we write specific functions in more complex front-end code.

While they do play nicely with each other, what they actually do can be a little confusing, so let’s check them out.

Iterators

Iteration is a common practice in programming and is usually used to loop over a set of values, either transforming each value, or using or saving it in some way for later.

In JavaScript, we’ve always had for loops that look like this:

for (var i = 0; i < foo.length; i++){
  // do something with i
}

But ES6 gives us an alternative:

for (const i of foo) {
  // do something with i
}

This is arguably way cleaner and easier to work with, and reminds me of languages like Python and Ruby. But there’s something else that’s pretty important to note about this new kind of iteration: it allows you to interact with elements of a data set directly.

Imagine that we want to find out if each number in an array is prime or not. We could do this by coming up with a function that does exactly that. It might look like this:

function isPrime(number) {
  if (number < 2) {
    return false;
  } else if (number === 2) {
    return true;
  }

  for (var i = 2; i < number; i++) {
    if (number % i === 0) {
      return false;
      break;
    }
  }

  return true;
}

Not the best in the world, but it works. The next step would be to loop over our list of numbers and check whether each one is prime with our shiny new function. It’s pretty straightforward:

var possiblePrimes = [73, 6, 90, 19, 15];
var confirmedPrimes = [];

for (var i = 0; i < possiblePrimes.length; i++) {
  if (isPrime(possiblePrimes[i])) {
    confirmedPrimes.push(possiblePrimes[i]);
  }
}

// confirmedPrimes is now [73, 19]

Again, it works, but it’s clunky and that clunkiness is largely down to the way JavaScript handles for loops. With ES6, though, we’re given an almost Pythonic option in the new iterator. So the previous for loop could be written like this:

const possiblePrimes = [73, 6, 90, 19, 15];
const confirmedPrimes = [];

for (const i of possiblePrimes){
   if ( isPrime(i) ){
      confirmedPrimes.push(i);
   }
}

// confirmedPrimes is now [73, 19]

This is far cleaner, but the most striking bit of this is the for loop. The variable i now represents the actual item in the array called possiblePrimes. So, we don’t have to call it by index anymore. This means that instead of calling possiblePrimes[i] in the loop, we can just call i.

Behind the scenes, this kind of iteration is making use of ES6’s bright and shiny Symbol.iterator() method. This bad boy is in charge of describing the iteration and, when called, returns a JavaScript object containing the next value in the loop and a done key that is either true or false depending on whether or not the loop is finished.

In case you’re interested in this sort of detail, you can read more about it on this fantastic blog post titled Iterators gonna iterate by Jake Archibald. It’ll also give you a good idea of what’s going on under the hood when we dive into the other side of this article: generators.

Continue reading %ES6 Generators and Iterators: a Developer’s Guide%

Powered by WPeMatico

The featured image was randomly selected. It is an unlikely coincidence if it is related to the post.