1

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

elements.map(element => {
  return {...element, selected: false};
})
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Mateusz Witkowski
  • 1,646
  • 10
  • 24
  • 1
    FWIW: `...` isn't an operator (it can't be; operators have a single result value), and in the context above, `...` is *spread* syntax, not rest syntax. – T.J. Crowder Dec 08 '17 at 11:44
  • You're right about rest vs spread. But are you sure about 'operator'? They use that name in MDN (see last part of URL) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator and in Microsoft Docs: https://learn.microsoft.com/en-us/scripting/javascript/reference/spread-operator-decrement-dot-dot-dot-javascript – Mateusz Witkowski Dec 08 '17 at 11:54
  • 1
    Yes, quite sure. :-) You won't see it called an operator in [the spec](https://tc39.github.io/ecma262/) or [the proposal](https://github.com/tc39/proposal-object-rest-spread). (Again: It can't be an operator, it doesn't have a single result value and can't be used in all expression contexts). Remember that MDN is community-edited. It's very good, but every once in a while someone introduces errors. The original author of that page did, unfortunately, include "operator" in the title. The article was fixed long ago, but sadly the URL remains. Can't give you a reason for MS getting it wrong. :-) – T.J. Crowder Dec 08 '17 at 12:01

1 Answers1

5

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Is it safe to use object spread operator? – sabithpocker Dec 08 '17 at 11:39
  • @sabithpocker: It's not an operator. It depends on your target environment and whether you're transpiling. Property rest/spread is currently a [Stage 3 proposal](https://github.com/tc39/proposal-object-rest-spread) but it's shipping in current versions of Chrome and Firefox (I don't have Edge handy), so may be near Stage 4. It's almost certainly going to be in the ES2018 snapshot spec. (But the question wasn't about property rest/spread, but rather, arrow functions. :-) ) – T.J. Crowder Dec 08 '17 at 11:42
  • Okay, thanks. Someone warned me from using it (in Typescript) while answering another question. Just wanted to know if its a valid warning. – sabithpocker Dec 08 '17 at 11:44