krsna
krsna

Reputation: 4333

When do we have to use () and {} in ES6 Arrow Functions

I'm little confused with the usage of parenthesis and flower brackets interchangeably in arrow functions.

For instance,

Use of Flower brackets

const sayHello = () => { console.log('Hello') }

Use of Parentheses

const sayHello = () => ( console.log('Hello') )

Both gives same output on the console. Do they both mean same? Sorry if this question sounds dumb.

Upvotes: 1

Views: 109

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44107

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.

Upvotes: 2

When you use "flower brackets" as you put it, it's like you're defining an ordinary function, having multiple statements as usual. In your example, it runs console.log('Hello') and doesn't return anything. When you use parentheses, you can specify only a single expression, and then the result of that expression becomes the return value. In other words, => (bar) is basically the same as => { return bar; }. Both work the same in your case since you're only using that function for its side effects and don't care about its return value.

Upvotes: 0

Related Questions