Reputation: 410
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
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