Subomi
Subomi

Reputation: 410

Why do we have to define Symbol.iterator with [Symbol.iterator] ? for iterables in javascript?

Why do we have to use those [] to define a @@iterator protocol in js.

// Works smoothly
var iterable = {
   [Symbol.iterator]() {}
}

// This fails with SyntaxError: unexpected token . 
var iterable = {
   Symbol.iterator() {}
}

Upvotes: 2

Views: 138

Answers (1)

deceze
deceze

Reputation: 522081

Because keys in object literals must be valid identifiers ("variable names") and are taken literally as the name as given. If you want to use an expression as the key (the value of Symbol.iterator, not the literal name "Symbol.iterator"), you need to use the computed property { [...]: ... } syntax.

Upvotes: 2

Related Questions