Chapter 5. ES6 Iterators and Generators

So far, we have discussed language constructs of JavaScript without looking at any specific language version. In this chapter, however, we will primarily focus on a few language features introduced in ES6. These features have a big impact on how you write JavaScript code. Not only do they improve the language significantly, they also offer several functional programming constructs unavailable to JavaScript programmers thus far.

In this chapter, we will take a look at newly introduced iterators and generators in ES6. With that knowledge, we will proceed to take a detailed look at the enhanced Collections constructs.

For...of loop

For...of loops are introduced in ES6 along with the iterable and iterator constructs. This new loop constructs replaces both the for...in and for...each loop constructs of ES5. As the for...of loop supports the iteration protocol, it can be used on built-in objects such as arrays, strings, maps, sets, and so on, and custom objects that are iterables. Consider the following piece of code as an example:

    const iter = ['a', 'b']; 
    for (const i of iter) { 
      console.log(i); 
    } 
    "a" 
    "b" 

The for...of loop works with iterables and built-ins like arrays are iterables. If you notice, we are using const instead of var when we define the loop variable. This is a good practice because when you use const, a fresh variable is created with a new binding and storage space. You should use const over a var declaration with the for...of loop when you don't intend to modify the value of the loop variable inside the block.

Other collections support for...of loop too. For example, as a string is a sequence of Unicode characters, for...of loop works just fine:

    for (let c of "String"){ 
      console.log(c); 
    } 
    //"s" "t" "r" "i" "n" "g" 

The main difference between the for...in and for...of loop is that the for...in loop iterates through all enumerable properties of an object. For...of loop has a specific purpose, and that is to follow the iteration behavior based on how the object defines the iterable protocol.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.42.208