Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do parenthesis surrounding brackets in the return statement of an ES6 arrow function do?

For example in redux actions, I've seen in someone's code:

export const updateMessage = text => {
   return (dispatch) => {
     dispatch(updateChatMessage(text))
   }
}

and:

const updateChatMessage = text => ({
   type: types.someActionType,
   text
})

it seems to function as an imply a return but I thought that was already implied in an arrow functions brackets following the fat arrow.

What do the parenthesis ({...}) do? are they necessary? Is there an alternate way to accomplish the same thing?

like image 491
Jim Avatar asked Oct 14 '25 15:10

Jim


2 Answers

when you write myFunction = value => ({prop: value}) it return the object {prop: value}, in this case {} are object delimiter and not 'function delimiter'

const updateChatMessage = text => ({
   type: types.someActionType,
   text
})

another eg :

when you want to multiply by two each elem of an array you can write :

array.map(elem => {return elem * 2})

or

array.map(elem => elem * 2) //same result

and if you want an eg with () that wrap an object litteral :

let array = [{val: 2},
             {val: 4},
             {val: 8},
             {val: 16}];
             
let output = array.map( ({val}) => ({val: val*2}) );

console.log(output);
like image 85
Simon Dehaut Avatar answered Oct 17 '25 09:10

Simon Dehaut


If you wrap the brackets with parenthesis you are making your function return an object literal (thus you don't need the return keyword). If you don't use parenthesis you have to use the return keyword.

like image 43
helado Avatar answered Oct 17 '25 07:10

helado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!