7

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?

0

1 Answer 1

11

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`
});
Sign up to request clarification or add additional context in comments.

2 Comments

Correct, and in that example, the block of code has a label "name" developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. There's no return statement in that block so the returned value is undefined
Yes @Tomasz - just getting round to that!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.