Square Brackets JavaScript Object Key

Square Brackets Javascript Object Key

It's the new ES2015 (the EcmaScript spec formally known as ES6) computed property name syntax. It's a shorthand for the someObject[someKey] assignment that you know from ES3/5:

var a = "b"
var c = {[a]: "d"}

is syntactic sugar for:

var a = "b"
var c = {}
c[a] = "d"

Why put an object key in square brackets (not destructuring)?

This is a computed property - it's the equivalent of:

let result = {}
result[CALL_API] = { ... };
return result;

Combining this with Symbol lets the library author create a protocol that will not collide with other protocols (e. g. if the protocol was a string "call" then it could collide with other libraries that use someObject.call for their (unrelated) protocols - as well as colliding with Function.prototype.call.)

What is the significance of double square brackets in javascript property names when initializing the object?

In ES6, [expression]: value is interpreted as follows:

  • evaluate expression
  • convert the result to a string
  • use this string as a key

Respectively,

 given [ [a] ]: 'boo'

evaluate [a] => ['foo']
String ['foo'] => 'foo'
result => {'foo': 'boo'}

In other words, extra brackets are ignored.



Related Topics



Leave a reply



Submit