Subomi.js Subomi.js - 6 months ago 34
Javascript Question

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() {}


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.