Creating an iterable in JavaScript

Let's create a real iterable object that can be iterated through a for-of loop. To do this, the object needs to add the appropriate function to Symbol.iterator.

Let's implement it. Let's have the following object:

let obj = { a: 1, b: 2, c: 3, };

We add a function to Symbol.iterator:

obj[Symbol.iterator] = function() { }

And turn this function into a generator:

obj[Symbol.iterator] = function *() { }

Inside our function, this will refer to the object itself:

obj[Symbol.iterator] = function *() { console.log(this); // the object itself }

Let's start iterating over the object in the iterator:

obj[Symbol.iterator] = function *() { for (let key in this) { yield obj[key]; } }

That's it, the object can be iterated with a for-of loop:

for (let elem of obj) { console.log(elem); // 1, 2, 3 }

Make an object that can be looped over with for-of. Let the loop element contain an object whose key key will contain a key of the object being iterated, and the val key will contain a value. An example:

let obj = {a: 1, b: 2, c: 3}; for (let elem of obj) { console.log(elem); }

It will output:

{key: 'a', val: 1} {key: 'b', val: 2} {key: 'c', val: 3}
enru