Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can object key be of Symbol.iterator type

Tags:

javascript

I know that ES5 object keys are of String type. If I specify anything else for object key, for example it will be converted to string:

var o = {}
var f = function() {}
// `toString` method is called on f
o[f]= 3

In this article I see that Symbol.iterator is used as a key:

let iterable = {
    [Symbol.iterator]() {
        let step = 0;
        let iterator = {
            next() {
                if (step <= 2) {
                    step++;
                }
                switch (step) {
                    case 1:
                        return { value: 'hello', done: false };
                    case 2:
                        return { value: 'world', done: false };
                    default:
                        return { value: undefined, done: true };
                }
            }
        };
        return iterator;
    }
};

So is Symbol.iterator coerced into a string?

like image 992
Max Koretskyi Avatar asked Dec 01 '25 07:12

Max Koretskyi


1 Answers

Short answer: Symbol.iterator does not coerce into string.

[Symbol.iterator] A zero arguments function that returns an object, conforming to the iterator protocol.

"Symbol.iterator" is a method that returns the default Iterator for an object. Called by the semantics of the for-of statement.

Look at this example:

var iterator = 'hi'[Symbol.iterator]();
iterator + "";                               // "[object String Iterator]"

iterator.next();                             // { value: "h", done: false }
iterator.next();                             // { value: "i", done: false }
iterator.next();
typeof Symbol.iterator;      // "symbol"
Symbol.iterator.toString();  // "Symbol(Symbol.iterator)"

Also a Symbol does not coerce into a string.

To create a new primitive symbol, you write Symbol() with an optional string as its description:

var sym1 = Symbol();
var sym2 = Symbol("foo");
var sym3 = Symbol("foo");

The above code creates three new symbols. Note that Symbol("foo") does not coerce the string "foo" into a symbol. It creates a new symbol each time: Resouce

like image 85
GibboK Avatar answered Dec 02 '25 20:12

GibboK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!