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

早过忘川 提交于 2021-02-11 15:45:53

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/61636153/meaning-of-curly-braces-in-array-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!