Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of curly braces in array.map() [duplicate]

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

like image 636
D Park Avatar asked Oct 23 '25 19:10

D Park


1 Answers

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”.

like image 198
hackape Avatar answered Oct 26 '25 07:10

hackape