1
let obj = {
  a: 'alex',
  [Symbol.iterator] : function* () {
    yield this.a;
  }
}

Came across this code when learning about Generator. Wondering what is the term for such syntax [Symbol.iterator] where we use [] to surround object property? Can we apply it to any other property or it's only for Symbol.iterator?

Also, is it possible to make it reusable just like any other function for example as below code

let obj = {
  a: 'alex',
  [Symbol.iterator] : function* () {
    yield this.a;
  },
  getA: function() {
    return this.a
  }
}


console.log(obj.getA())//Perhaps obj.[Symbol.iterator]()............... ?
Isaac
  • 8,290
  • 6
  • 32
  • 69
  • 1
    [Computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) – Phil May 31 '18 at 03:08
  • 2
    Possible duplicate of [What do square brackets around a property name in an object literal mean?](https://stackoverflow.com/questions/34831262/what-do-square-brackets-around-a-property-name-in-an-object-literal-mean) – Robby Cornelissen May 31 '18 at 03:09

1 Answers1

3

In modern JavaScript, a bracketed property name like [Symbol.iterator] means that the expression in the brackets should be evaluated to determine the property name in the declaration.

The expression Symbol.iterator evaluates to a Symbol instance for the distinguished property to identify the iterator function property of an iterable object.

In "old fashioned" JavaScript the code could have been written as:

let obj = {
  a: 'alex',
  getA: function() {
    return this.a
  }
};

obj[Symbol.iterator] = function* () {
    yield this.a;
};

(Obviously that's not really "old-fashioned" JavaScript because the Symbol feature is new, but hopefully it's clear.)

Pointy
  • 371,531
  • 55
  • 528
  • 584