Reputation: 1045
when I have:
const foo = 1;
I can set a shorthand for object property names
const bar = {foo}
thats the same like
const bar = {foo: foo} // bar will be {foo: 1}
is there a shorthand when I have a const with an arrow function?
const foo = () => 1
i have to set it like this, but its uncool
const bar = {foo: foo()}
I would like to do it like this or something thats shorter
const bar = {foo()} //bar should be {foo: 1} but this will fail
Upvotes: 3
Views: 1559
Reputation: 42430
The symmetry is already there. {foo}
is equivalent to {foo: () => 1 }
, i.e. an object containing a property foo which is a function. E.g. you could then call it like this if you wanted:
bar.foo();
Your request seems to be for new syntax that instead calls foo
and populates bar.foo
with the result. There's no such syntax. What if foo
takes arguments? What if foo
is asynchronous (you'd want to use await
then)? How did you end up with functions with the same name as properties? Without a demonstrated use-case, it's hard to see any value in optimizing for this pattern.
Shorter isn't always more readable.
If you have a set of functions dedicated to providing the results for a set of same-named properties, you could perhaps construct something, using a mapObject helper, like this:
const mapObj = (o, f) => Object.assign({}, ...Object.keys(o).map(k => ({[k]: f(o[k])})));
const foo = () => 1;
const fum = () => 2;
let bar = mapObj({foo, fum}, f => f());
console.log(JSON.stringify(bar));
Upvotes: 1
Reputation: 1045
Ok I forgot that there are also IIFE possible with arrow functions.
so if you like the benefit of this shorthand you can do
const foo = (() => 1)()
const bar = {foo}
downside: you need an IIFE
Upvotes: 0
Reputation: 10209
Looking at the specs, there's no syntax for this.
In your case ObjectLiteral
must resolve to { PropertDefinitionList }
, which must resolve to PropertyDefinition
. Now what could PropertyDefinition
be?
It can't be IdentifierReference
- that's your first example: {f}
.
CoverInitializedName
doesn't really fit either. That would look like {f = AssignmentExpression}
where AssignmentExpression
is defined here.
PropertyName: AssignmentExpression
is the conventional syntax: {f: 1}
MethodDefinition
lets you do {f(){ return 1; }};
, but that again isn't what you want.
Looks like the verdict is no.
Upvotes: 6