In a previous post we looked at using iterators directly. Working with iterators at a low level will sometimes be useful, as we’ll see in future posts, but ES6 also provides a new looping syntax to work with iterators at a higher level – the for of loop.
let sum = 0; let numbers = [1,2,3,4]; for(let n of numbers) { sum += n; } expect(sum).toBe(10);
There are a couple observations to make about the above code.
First, the new for of loop looks much like the for in loop, which has always been around, but the two are subtly different. The for in loop works with the enumerable properties of any object, thus when working with an array, for in will iterate over the available indexes of the array, not the available values. To compute the same sum as the above code with for in, we’d need to index into the array with each iteration:
let sum = 0; let numbers = [1,2,3,4]; for(let i in numbers) { sum += numbers[i]; // notice the indexer } expect(sum).toBe(10);
The for of loop uses an iterator to visit the values in an array, not the available keys.
for(let n of numbers) { sum += n; }
This brings up the second subtle difference with for of, the for of loop exists not to work with just any type of object, but with iterable objects. Iterable objects are objects with a special method returning an iterator. We’ll look at the special method in a future post, but notice how the above code doesn’t need to use the values method of the array like the low level iterator code we wrote in the last post. The for of loop uses the numbers array directly.
There are many objects in the world of ES6 that will be iterable objects, and we will see more in future posts. For now, we’ve already seen how arrays are iterable. Strings are also iterable (you can iterate over the sequence of characters inside).
let result = ""; let message = "Hello"; for(let c of message) { result += c; } expect(result).toBe("Hello");
How does does for of retrieve an iterator? And what makes an object iterable? To answer these questions we have to take a brief detour into another new feature of ES6 – the Symbol.