When you use curly braces (flower brackets) it defines the function body - so you can place multiple semicolon-separated statements inside them. If you wish to return a value from the function, you must explicitly use the return
statement.
If you use parentheses, you are going to be returning the value of the expression inside the parentheses, and there can only be one expression (with no semicolon). If you wish to do multiple things with parentheses, you can use the comma operator:
const doTwoThings = () => (console.log("Hello"), console.log("Goodbye"));
console.log(doTwoThings());
Here, you're logging Hello
, then Goodbye
, then you're logging the return value of the function - which is undefined
.
You can do the same thing inside the curly braces, and you won't see any visible difference:
const doTwoThings = () => {console.log("Hello"), console.log("Goodbye")};
console.log(doTwoThings());
Again you're logging Hello
and Goodbye
to the console, then you're logging the return value of the function - however, using {}
needs to have the explicit return
keyword, so it's undefined
because we don't return anything from the function.
Also note that sometimes you'll see both parentheses and curly braces:
const aFunction = () => ({ foo: "bar" });
console.log(aFunction());
There's a nice explanation here, but basically when you have a function returning an object, the curly braces {}
denote the object, and the parentheses enforce the implicit return of the contained expression - the object. So the object is created, then the expression is evaluated and returned.