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
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”.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With