cade galt
cade galt

Reputation: 4161

What do square brackets around a property name in an object literal mean?

Considering the following object literal:

{
  files: {
    [bpr + 'lib/Monster.min.js']: ['<%= concat.dist.dest %>']
  }
}

What does the []: [] syntax do?

Upvotes: 43

Views: 12744

Answers (2)

Matt
Matt

Reputation: 44058

This is called a "computed property name" and was added with ES6.

From MDN:

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed as the property name.

Upvotes: 61

Justine Mahinyila
Justine Mahinyila

Reputation: 146

In ES6 square bracket is part of os the object literal when using computed key pairs.

For example:-

Problem Below the string "key" times 5 makes a computed key named "key"*5, now without using square brackets this result in a syntax error

const newObject = {
    "key"*5:"value"
}

The Solution The solution will be to use a square bracket before using a computed property as a key

const newObject = {
    ["key"*5]:"value"
}

For more reference of how to create objects check out this link

Upvotes: 7

Related Questions