DEV Community

Discussion on: There's no "else if" in JS

 
kepler1359 profile image
Kepler1359

can someone explain to me why you can use parathesis instead os curly braces with an arrow function? I was thought that the parathesis are used to indicate to the compiler that what is encapsulated in the parathesis are supposed to be treated as parameters, and what is in the curly braces are supposed to be treated as the logic.

This goes to the point trying to be made by Fabio Russo "the good parts or right ways to code...It's not really the best way."

Thread Thread
 
mahlongumbs profile image
Mahlon Gumbs • Edited

Your information is not incorrect for regular functions. However, with an arrow function, you are allowed to use parentheses to represent a function body with a single statement (useful when spanning multiple lines).

There are other places you can omit things as well.

Examples:

Single parameter, parentheses are optional

const myFunc = (singleParam) => {/* function body */};
// is the same as
const myFunc = singleParam => {/* function body */};

Multiple parameters require parentheses

const myFunc = (param1, param2) => {/* function body */};
const myFunc = param1, param2 => {/* function body */}; //Syntax error due to missing parentheses

Function body needs curly braces for multi-line command block

const myFunc = param1 => {
  console.log('I did something');
  console.log('I did something else');
};

However, if your body is a single line and you want to return the result, you may do any of the following (all of these return the value of name.toUpperCase()

const myFunc = name => {
  return name.toUpperCase(); // note the return
};

const myFunc = name => (
  name.toUpperCase(); // note, no return if in parentheses
);

const myFunc = name => name.toUpperCase();

It really helps if you have a command that spans multiple lines where you just want to return the result. So, for example, if you were dealing with a promise you could do either of the following:

const fetchUser = userId => (
  fetch(`http://example.com/user/${userId}`)
    .then(rsp => rsp.data)
    .catch(error => {
      console.log(error);
    };
);

const fetchUser = userId => {
  return fetch(`http://example.com/user/${userId}`)
    .then(rsp => rsp.data)
    .catch(error => {
      console.log(error);
    };
};
Thread Thread
 
kepler1359 profile image
Kepler1359 • Edited

Now, I understand that you're able to use arrow functions in more diverse ways, but after looking at the code I had trouble with I realize that pranay rauthu used a "hidden if-statement" how does one use the ampersand(&) to make a conditional, and to see if arg === some-value, and print a value based on what the client set arg equal to.

If someone has a response to my question, please point me to some resource so I can deepen my knowledge on javascript