Subomi.js Subomi.js - 1 year ago 62
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() {}

Answer Source

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.