5

I am running the following in node and can't understand why one works and why the other doesn't. Here I have an array s where s = [1, 2, 3, 4]. I want to map each number to an object. I've been trying this for a long time:

s.map(i => {name: i})

which returns a list of undefined.

Finally I realized it worked with parenthesis:

s.map(i => ({name: i}))

This provides the output I want: [ { name: 1 }, { name: 2 }, { name: 3 }, { name: 4 } ]

I feel like there is a JavaScript concept I am not understanding. Why does this not work?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Timothy Deng
  • 474
  • 3
  • 16

1 Answers1

9

This is because => { represents a block function, not returning an object.

Wrapping the object in parentheses does nothing, it simply interrupts that pattern => {, meaning it's interpreted as a concise arrow function rather than a block arrow function, and you can return the object.

So, if you want to return an object, you can either wrap it in parentheses (this is the easiest way):

s.map(i => ({ name: i }));

Or use a block function:

s.map(i => {
  return { name: i };
});

(on a side note, you can make your function more concise by passing in name as the map parameter name:

s.map(name => ({ name }));

As pointed out by Tomasz below, the reason that your first attempt returned a list of undefined was because name: is the syntax for a label in JavaScript - and you were just labelling name: then stating the variable i - so your code basically looked like this ES5:

s.map(function(i) {
  name: i
  // No return so it returns `undefined`
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 1
    Correct, and in that example, the block of code has a label "name" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label. There's no return statement in that block so the returned value is `undefined` – Tomasz May 08 '20 at 02:14
  • Yes @Tomasz - just getting round to that! – Jack Bashford May 08 '20 at 02:17