const actionsMap = {
[GET_USER]: (state, action) => ({ post: action.msg })
};
I have this code that I've stumbled upon. All the time I've been working with arrow functions I've seen on a {} format, what does this () wrapper mean?
With arrow functions, you can either use a single statement or a block as the function body. These two are equivalent:
() => foo
() => {
return foo;
}
In your example, if the lambda was defined as () => {post: action.msg}
the object ({}
) would be interpreted as a body block instead of an object. The runtime would try to parse it as an equivalent to:
function () {
post: action.msg
}
which is a named label and property access, and doesn't make much sense here. By wrapping in parens, you hint to the parser that it is an expression to be evaluated and the fat arrow function rules on single-expression bodies kick in, making it equivalent to:
function () {
return {post: action.msg};
}
To work around the single-expression rules when you want to do two related things (occasionally useful in map/reduce algorithms), you can use parens to group a pair of expressions:
foo.reduce((p, c) => (c.counted = true, p += c.value));
This will set the counted
property of c
, before adding c.value
to p
and returning the result of p += c.value
as the new value of p
.
The parentheses wrap an expression in ECMAScript and can be used, with the comma operator, to group multiple expressions. The results of the last expression are returned when the group is evaluated.
For example:
var i = 0, j = 0;
console.log((j += 10, i += 2), j);
will print 2 10
, since j
is incremented in the ()
group and printed later.