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:
JavaScript
x
6
1
const foo = (params) => (
2
<span>
3
<p>Content</p>
4
</span>
5
);
6
vs.
JavaScript
1
5
1
const handleBar = (e) => {
2
e.preventDefault();
3
dispatch('logout');
4
};
5
Advertisement
Answer
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:
JavaScript
1
14
14
1
const a = (who) => "hello " + who + "!";
2
const b = (who) => ("hello " + who + "!");
3
const c = (who) => (
4
"hello " + who + "!"
5
);
6
const d = (who) => (
7
"hello "
8
+ who
9
+ "!"
10
);
11
const e = (who) => {
12
return "hello " + who + "!";
13
};
14
You will also often see parenthesis around object literals because that’s a way to avoid the parser treating it as a code block:
JavaScript
1
3
1
const x = () => {} // Does nothing
2
const y = () => ({}) // returns an object
3