Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow function without curly braces

I'm new to both ES6 and React and I keep seeing arrow functions. Why is it that some arrow functions use curly braces after the fat arrow and some use parentheses? For example:

const foo = (params) => (     <span>         <p>Content</p>     </span> ); 

vs.

const handleBar = (e) => {     e.preventDefault();     dispatch('logout'); }; 
like image 370
dkimot Avatar asked Sep 22 '16 03:09

dkimot


People also ask

Do arrow functions need curly braces?

There are two ways to declare an arrow function: Without curly braces {} . With this syntax, the arrow function has an implicit return. For example, the below arrow function returns 42, even though there's no return .

When should you not use arrow functions?

An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.


2 Answers

The parenthesis are returning a single value, the curly braces are executing multiple lines of code.

Your example looks confusing because it's using JSX which looks like multiple "lines" but really just gets compiled to a single "element."

Here are some more examples that all do the same thing:

const a = (who) => "hello " + who + "!"; const b = (who) => ("hello " + who + "!"); const c = (who) => (   "hello " + who + "!" ); const d = (who) => (   "hello "     + who     + "!" ); const e = (who) => {   return "hello " + who + "!"; };  

You will also often see parenthesis around object literals because that's a way to avoid the parser treating it as a code block:

const x = () => {} // Does nothing const y = () => ({}) // returns an object 
like image 197
david Avatar answered Oct 17 '22 04:10

david


One can also use curly braces to prevent a single line arrow function from returning a value -- or to make it obvious to the next developer that a single line arrow function shouldn't, in this case, be returning anything.

For example:

const myFunc = (stuff) => { someArray.push(stuff) } const otherFunc = (stuff) => someArray.push(stuff)  console.log(myFunc())    // --> logs undefined console.log(otherFunc()) // --> logs result of push which is new array length 
like image 29
GrayedFox Avatar answered Oct 17 '22 02:10

GrayedFox