Object literal shorthand problem

consider this code :

const getMousePosition = (x, y) => ( {
x: x,
y: y
} );

I understand this returns the object , but why after the arrow it starts with a bracket and not a curly brace? , I have never seen this syntax before.

It starts with a parentheses because when using arrow function syntax =>, if JavaScript sees a curly bracket first, it assumes the next statements are part of a block of code. To return an object directly after the =>, you must wrap the object literal with ( and ), so JavaScript knows you are wanting to return an actual object.

FYI - You can simply write { x, y } instead of { x: x, y: y }, since you are you want the property names to be the same as the values that x and y represent. It is shorthand.

const getMousePosition = (x, y) => ({ x, y });
1 Like

Thanks very useful !