Function definition when to use ( ) and when not to use them?

wrt chapter and coming from Java background, it is super confusing with flexible ways of defining function in JS

Way 1

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

Note parenthesis against the function body

Way 2

const createPerson = (name, age, gender) => {
  "use strict";
  // change code below this line
  return {
  // change code above this line
console.log(createPerson("Zodiac Hasbro", 56, "male")); // returns a proper object

No parenthesis in this case.

  • Please clarify when to use ( ) and when not to use it ?
  • Can I use ( ) in 2nd case ?


MDN is your friend any time you have doubt of this sort.

If you look at the documentation for arrow function you’ll see under the advanced syntax the following example:

// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})

or in other word, if you use pares around, means you want to return an Object.

So this are equivalent:

() => {
 const obj = { a:1, b:2 };
 return obj;

// equivalent to
() => ({ a:1, b: 2 })

Hope this helps :+1:


Thanks for quick clarifications.