3

I have a .map() function that changes isActive property value of objects in data array. However wraps it with curly braces returns me undefined whereas wrapping it with parenthesis or no wrap returns the updated value. Curly braces are used as a wrapper in an arrow function but does it work differently for .map()?

    const newData = data.map((data) => {
      data.label === label ? { ...data, isActive: !data.isActive } : data,
    });
    console.log(newData) 
    //undefined



    const newData = data.map((data) => 
      data.label === label ? { ...data, isActive: !data.isActive } : data,
    );
    console.log(newData) 
    //returns updated newData

D Park
  • 504
  • 10
  • 19
  • 1
    *"but does it work differently for .map()?"* No. `.map` doesn't know how the function was created, so whether or not you use `.map` has no impact on how the function is interpreted. – Felix Kling May 06 '20 at 13:15
  • 1
    Curly braces are for supporting multiline tasks. If your callback function body has multi-line codes then you have to wrap them in curly braces. And for a map, your must-have to return some value. For a single-line function, you need not use the `return` keyword. It automatically returns the value. – Sajeeb Ahamed May 06 '20 at 13:17

1 Answers1

9

That’s the behavior of arrow function. Arrow function syntax is designed to be terse.

(arg) => [single expression]

If what follows the arrow is one single expression without curly braces, it implies returning the value of that expression. The return keyword is omitted.

If wrapping curly braces follows the arrow, then what goes inside the braces are treated as normal function body, and return keyword must be used if you mean to return a value.

So (x) => x + 1 is translated to:

function (x) {
  return x + 1;
}

And (x) => { x + 1 } is translated to:

function (x) {
  x + 1;
}

I must also add that (x) => ({ x }) is translated to:

function (x) {
  return { x: x };
}

Curly brace {...} can mean an object literal, a function body or a code block.

In order to disambiguate, you need to put parenthesis around the braces to tell the parser to interpret {...} as an “object literal expression”.

hackape
  • 18,643
  • 2
  • 29
  • 57
  • 1
    *"The parenthesis around the braces is the syntax for an “object literal expression”"* No. `{...}` is the object literal. The parenthesis tell the parser to interpret `{` as the start of an expression, not an arrow function body. – Felix Kling May 06 '20 at 18:15
  • @FelixKling thanks for correcting me. I’m actually not sure how to phrase it with right word. Would you like to edit my answer directly? I appreciate that. – hackape May 07 '20 at 06:17