-1

Does the Object literal notation not work inside map function? I tried this in Node 12 and 15 REPL

> nums = [1,2,3,4]
[ 1, 2, 3, 4 ]
> nums.map(n => { n })
[ undefined, undefined, undefined, undefined ]
> nums.map(n => new Object({n}))
[ { n: 1 }, { n: 2 }, { n: 3 }, { n: 4 } ]
sgarg
  • 2,340
  • 5
  • 30
  • 42
  • 6
    `nums.map(n => ({ n }))`. Without the `()`, the `{}` is considered as a code block, not as an object literal. – adiga Nov 12 '21 at 15:11

1 Answers1

1

Try this:

nums.map(n => ({ n }))

Without the parentheses, { n } is being interpreted as the body of your function. By including parentheses, you're indicating that { n } should be implicitly returned instead.

Here is an overview of implicit vs. explicit returns, which should help provide some more detail.

Donut
  • 110,061
  • 20
  • 134
  • 146
  • oh god, thank you, is there a link to that paranthesis usage to understand it better? – sgarg Nov 12 '21 at 15:12
  • 1
    @sgarg please check the duplicates linked above your question https://stackoverflow.com/a/38015233 – adiga Nov 12 '21 at 15:13
  • cool, found https://stackoverflow.com/questions/45003702/what-do-the-parentheses-wrapping-the-object-literal-in-an-arrow-function-mean/45003753 – sgarg Nov 12 '21 at 15:14