A dynamic property:
var obj = {
  // Computed (dynamic) property names
  [ 'prop_' + (() => 42)() ]: 42
};
This is of course very fancy. But where could someone use this without adding unnecessary complexity?
A dynamic property:
var obj = {
  // Computed (dynamic) property names
  [ 'prop_' + (() => 42)() ]: 42
};
This is of course very fancy. But where could someone use this without adding unnecessary complexity?
 
    
    If you have a property name as a constant:
var obj = { [SOME_CONSTANT]: 42 };
 
    
    One case where I wanted it was where property names for JSON were defined in generated files, based off Java classes.
// Generated
var SomeJsonBodyParams = {NAME: 'name', ID: 'id', ETA, 'estimatedTimeOfArrival'};
// Using it
sendAjax('some/url', {
    [SomeJsonBodyParams.NAME] = userData.name,
    ...
});
We even had a method so we could kind of do it
function makeObj() {
  var obj = {};
  for (var i=0; i < arguments.length; i+=2) {
      obj[i] = obj[i+i];
  }
  return obj;
}
sendAjax('some/url', makeObj(
    SomeJsonBodyParams.NAME, userData.name,
    ...
));
 
    
    Let's say you have:
var hi = 'hi';
var test = 'test';
var hello = 'hello';
Instead of:
var object = {};
object[hi] = 111;
object[test] = 222;
object[hello] = 333;
You could write it in a much shorter syntax:
var object = {
    [hi]: 111,
    [test]: 222,
    [hello]: 333
}
 
    
    E.g. it could be used when you want to use a, let's say, constant as a key in object.
const DATA_TYPE = {
    PERSON: 'person',
    COMPANY: 'company'
};
let cache = {
    [DATA_TYPE.PERSON]: getPerson()
};
And later access:
cache[DATA_TYPE.PERSON]
Instead of DATA_TYPE.PERSON could be anything (including some real-time calculated values).
