1

Here is the code I am confused about:

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

I understand the arrow functions. For example,

const addOne = (x) => x + 1;

is the same as

const addOne = function(x) {
  return x + 1;
}

What I'm uncertain about is the parenthesis that surround the brackets in the top most code.

...({
  x: x,
  y: y
});

If they weren't there then the top most code would just return an object... Can someone explain to me what adding the parenthesis will do?

Thanks in advance.

Playground
  • 23
  • 3

1 Answers1

2

It's to return a JavaScript object, as in { a: 'b' } as opposed to that being interpreted as a code block like { a(); }.

In other words it expands to1:

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

1 Of course this behaves differently as per all arrow functions.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • Good answer, though I don't think mentioning the difference in context is necessary. It might be beneficial to explain that parentheses causes the expression to be evaluated as a separate string of tokens relative to the code structure it is within. – zfrisch Oct 27 '20 at 18:46