Iteration

suggest change

A generator is iterable. It can be looped over with a for...of statement, and used in other constructs which depend on the iteration protocol.

function* range(n) {
    for (let i = 0; i < n; ++i) {
        yield i;
    }
}

// looping
for (let n of range(10)) {
    // n takes on the values 0, 1, ... 9
}

// spread operator
let nums = [...range(3)];  // [0, 1, 2]
let max = Math.max(...range(100));  // 99

Here is another example of use generator to custom iterable object in ES6. Here anonymous generator function function * used.

let user = {
  name: "sam", totalReplies: 17, isBlocked: false
};

user[Symbol.iterator] = function *(){

  let properties = Object.keys(this);
  let count = 0;
  let isDone = false;

  for(let p of properties){
    yield this[p];
  }
};

for(let p of user){
  console.log( p );
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Generators:
* Syntax
* Iteration

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
37 Generators
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde