Does anyone know why it requires parenthesis () wrapped around the object after “item =>”?
const products = [
{
id: 1,
name: 'pencil',
price: 1,
description: "Perfect for those who can't remember things! 5/5 HIghly recommended."
},
{
id: 2,
name: 'Housing',
price: 0,
description: "Housing provided for out-of-state students or those who can't..."
},
]
const productItems = products.map(item => ({id: item.id, // what does the parenthesis here stand for? why is it needed?
name: item.name,
price: item.price,
description: item.description}))
What do you mean by “function”?
Could you please explain more?
I just followed fCC curriculum. From what I learned, it makes sense to me to have curly braces since it is generating an object, but what is parenthesis here standing for?
However, if you want to return an object without creating an external variable (like above):
const myFunc = () => ({ example: 1 });
Essentially, without the parentheses, the function is interpretted as:
function myFunc() { example: 1 }
If you can see the syntax highlighting, the interpreter is not happy. Did I want an object literal after myFunc(), or did I want to open the function with myFunc() {?
I don’t understand where this extra parenthesis comes from… or we just need to add it as an extra to make it work particularly for the case when the return is an object?
Right, in JS you cannot start an expression with a curly brace or JS will assume it is a code block. This creates this problem with objects. It wouldn’t be a problem with say, an implicit return of an array, because that doesn’t start with a curly brace.
A similar problem can manifest itself when trying to destructure into a previously declared variable:
const myObject = { p1: 1, p2: 2 };
let p1, p2;
{ p1, p2 } = myObject; // seems like it should work but doesn't
({ p1, p2 } = myObject); // parentheses save the day
const myArray = [1, 2];
let el1, el2;
[el1, el2] = myArray; // not a problem becauce doesn't start with a curly brace