Symbol.iterator

2 0 0
                                        

Iterating - means you want to keep on looping just to view each item from the start to the last.

Symbol.iterator - this returns a default iterator to an object. You usually add this to your own object. So, you can iterate into it.

How it works?

=====================

let colors = {

    0: "Red",

    1: "Orange",

    2: "Yellow",

    3: "Green",

    4: "Blue",

    5: "Indigo",

    6: "Violet",

    start: -1,

    length: 6

   [Symbol.iterator]: function(){

        return {

            current: this.start,

            last: this.length,

            next(){

                if(this.current++ < this.last){

                    return {

                        done: false,

                        value: colors[this.current]

                    }

                }else {

                    return {

                        done: true

                    }

                } 

            }

        };

    }

};

function displayTheColors(){

    for(let color of colors){

        document.writeln(color);

    }

}

=====================

HTML:

displayTheColors()

Result:

Red Orange Yellow Green Blue Indigo Violet


Note: 

1, Symbol.iterator always looks for the next() method. 

2. This next() method should return an object. 

3. For the returned object, the keys should be named "done" and "value".

4. The key "done" should have a value of boolean. The key "value" is any value you want to return from the object. Be careful of the shadowing of the this keyword.

5. The keys "start" and "length" was just used for the purpose of increments and conditions just like in a while loop. You can change the name if you like. 


Implicit usage of Symbol.iterator in a for..of

================

fun displayTheMessage(){

    let message = "Hello World";

    for(let char of message){

        document.writeln(char);

    }

}

=================

HTML:

displayTheMessage()

Result:

H e l l o W o r l d


Explicit usage of Iterator

=================

fun displayTheMessage(){

    let message = "Hello World";

    let iterator = message[Symbol.iterator]();

    let obj = iterator.next();

    document.write('done: ${obj.done} and value: ${obj.value}');

}

================

HTML:

displayTheMessage()

Result:

done: false and value: H

Note: I just display it instead of iterating it because the retrieving of done is slow.



Javascript ProgrammingWhere stories live. Discover now