1

I just started JS, wondering why there are [] around Symbol. For example: in an object.

var bow = {
    [Symbol('apple')] : something,
    [Symbol('banana')] : something, 
    ....
}

Also, when it comes to iterator:

var iterableObject = {
    [Symbol.iterator] : function() {.....}
}

Can anyone explain what is the use of these [] around them? I googled a while but didn't find satisfied answer, thank you in advance.

Potter
  • 605
  • 6
  • 12
dex
  • 57
  • 2
  • 10

2 Answers2

2

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

The bracket notation is just another way of accessing a property on an object. In particular, it's used when the property name is not valid for use with the dot notation, such as Symbol.iterator.

You may also want to look at computed property names: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names

These are similar but are instead used to set properties when an object is defined rather than get properties from an already defined object.

CRice
  • 22,449
  • 3
  • 48
  • 54
2

The square brakets are just part of object literal syntax.

When you make an object using object literal syntax it is now possible to use variables to set the keys inside the object.

const string = 'whatever'
const normalObject = {
    [string]: 'something else'
}

This results in normalObject having one property, 'whatever' pointing to 'something else'

// normalObject
{ whatever: 'something else' }

The use of brackets in object literal syntax is just to allow you to use a variable to set the key in an object.

bringing this back to your example this is just allowing you to use Symbols as keys in your object.

You may have noticed that this is a little weird. Up until very recently an object could only have String keys. Symbols are not the other thing you can use as keys in an object.

var bow = {
    [Symbol('banana')] : something,
    [Symbol('banana')] : something, 
    ....
}

this will result in an object with two different Symbol(banana) pointing to something.

Potter
  • 605
  • 6
  • 12