2
var o = {["k"](){}}; // {k: ƒ}
o.k();

Here you can see an example:

enter image description here

How {["k"](){}} is compiled to an object which has a key k inside which is a function?

1 Answers1

8
{["k"](){}}

equals:

{
  k(){}
}

Which is ES2015 short method syntax for:

{
  k: function(){}
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 3
    What's the purpose of `["k"]` vs. `k`? – tadman Nov 10 '17 at 20:46
  • 5
    @tadman its intended for dynamic keys, e.g. `[key]:value` ( the usecases are rare but they exist) , if used with a string in it its rather a missuse – Jonas Wilms Nov 10 '17 at 20:47
  • 1
    @tadman See [object initializers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), in particular the part on computed properties. However, in this case, I think `{["k"](){}}` and `{k(){}}` are equivalent. – CRice Nov 10 '17 at 20:47
  • Thanks, it is hard to Google. Reference: [Object initializer - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) –  Nov 10 '17 at 20:48
  • Sure it's ES2015 and not ES6? – ibrahim mahrir Nov 10 '17 at 20:50
  • 3
    @ibrahim aren't they equal? – Jonas Wilms Nov 10 '17 at 20:50
  • 2
    Im sometimes surprised by votes on SO. Thats my second best answer of all time based on votes, and i mean thats just 8 words :/ – Jonas Wilms Nov 10 '17 at 20:55
  • @JonasW. [**I know exactly how do you feel**](https://stackoverflow.com/questions/46230125/what-is-map-doing-in-this-situation/46230151#46230151). – ibrahim mahrir Nov 10 '17 at 20:58
  • @JonasW. right time, right place... :) – skyboyer Nov 10 '17 at 20:58
  • 1
    @JonasW. Take a look at my top-voted answers. – Barmar Nov 10 '17 at 21:23
  • Spend 30 minutes writing an extremely well written in depth answer, 500 views no votes. Tell someone about their typo... 5 views 5 votes. – Kyle Richardson Nov 10 '17 at 21:25
  • 1
    @tadman That's the reason for `["k"]` style: You could do `{["\""](){}}`. This creates a function named `"()` (very bad style!). But imagine a situation where you create object properties that are named by user input. Everything could be possible... – andy Nov 10 '17 at 21:32