30

I've been writing in JS for a while and have not used this form:

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

the

[]:[]

it works, I just have not used it or seen it before.

CoderPi
  • 11,946
  • 4
  • 28
  • 58
cade galt
  • 2,995
  • 5
  • 21
  • 43
  • 1
    sorry, I did not say the environment, I'm using Grunt from the command line and this is the Gruntfile.js that grunt uses. I needed a variable based key so I just tried it and it worked. But the answer, is yes, this is correct JavaScript ES6 but no correct for ES5. – cade galt Jan 16 '16 at 19:50
  • I read an article on ES6 and this probably should have been mentioned in the top 5 additions that ES6 give. Very nice. – cade galt Jan 16 '16 at 19:51
  • @cadegalt can you add the information about where this code can run in your question please? – CoderPi Jan 16 '16 at 19:51

2 Answers2

48

Only recently with ES6. They are called "computed property names"

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.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
Matt
  • 40,711
  • 6
  • 89
  • 98
0

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