Search code examples
javascripttypescriptarrow-functionsecmascript-next

rest operator returned by fat-arrow function


Is it possible to write the code below in one line (without return keyword)?

elements.map(element => {
  return {...element, selected: false};
})

Solution

  • Yes, by using the concise arrow form, enclosing the object initializer in ():

    elements.map(element => ({...element, selected: false}));
    // ---------------------^-----------------------------^
    

    You need the () because otherwise the { of the object initializer is read as the { as the beginning of a function body. The ( instead makes it an expression body with implied return.