Hi, this is one line from my code:
tasksArray = tasksArray.map((taskItem, index) => {id: index + 1, task: taskItem.task})
It is not working when it’s constructed like this, however then I’m adding the brackets around the object that is created for every array item (I mean like that ({id: index + 1, task: taskItem.task})
) it’s working excelent, why is that happening? I dont understand this syntax code, why shouldn’t we use curly brackets like we do with every function () => {}
???
Braces are used in arrow functions if you want it to be multi-line (just like in a regular function):
(x, y) => {
const z = x + y;
return z;
}
What’s happening in your arrow function is that the braces are interpreted as the beginning and end of a function body, not as an object literal. Kind of like:
function(taskItem, index) {
id: index + 1,
task: taskItem.task
}
Now that isn’t really what you want.
If you intend for an arrow function to return an object, you’ll need to wrap the braces with a set of parentheses. Basically JS will treat the code in the parentheses as a single value, in this case as a single object.
2 Likes