0

In legacy code for an Electron + Vue.js + ES7 project, there is Javascript using square brackets around the names of object elements, and I can't find the source of this syntax. Does this look familiar to you? Is it super-recent Ecmascript? Does this suggest a transpiler in the build that I'm not aware of?

const state = {
  [SUBMISSIONS]: [],
  [LAST_OPENED_ROW_ID]: -1
}

const mutations = {
  [SUBMISSION] (s, data) {
    return Object.assign(s, { [SUBMISSION]: data })
  }
}
customcommander
  • 17,580
  • 5
  • 58
  • 84
Lucas Gonze
  • 575
  • 1
  • 5
  • 13

3 Answers3

1

To set the key of an object to a variable you can encapsulate the variable in braces []

Somewhere, it was probably defined as:

const SUBMISSIONS = 'submissions'

It's a pattern that was heavily adopted in React environments.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
1

in this code [] are used to have dynamic keys,expression inside [] is resolved and final value is used as key name

let dynamic = 'some key'

let obj = {
  [dynamic] : 'some value'
}

console.log(obj)

Ref

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

That is computed property introduced in ES6.

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 and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you might have used to read and set properties already.

Browser compatibility for computed property names:

  • Chrome: From version 47
  • Edge: Supported
  • Firefox: From version 34
  • Internet Explorer: Not supported
  • Opera: From version 34
  • Safari: From version 8
  • Android webview: From version 47
  • Chrome for Android: From version 47
  • Firefox for Android: From version 34
  • Opera for Android: From version 34
  • Safari on iOS: From version 8
  • Samsung Internet: From version 5.0
  • Node.js: Supported

source

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • 1
    It was an odd choice to overload array initializer syntax to serve double duty for computed property name evaluation. Parsers/compilers have to differentiate based on context. Similar goings-on with curly braces and structured returns, but at least there you have `key:value` notation to differentiate. Perhaps a result of the limited non-printable symbol set available in UTF-8/ASCII 0-127 (where most of the first 32 chars are of no use to modern equipment). – Kevin-Prichard Sep 13 '19 at 21:41