Arrow function body vs. returning value. ()=>{return value;} vs. ()=>value;

Viewed 2519

Is there any difference between returning a value in an arrow function, vs adding the body and typing return?

As far as I'm aware they are the same.

Here's a session:

let a = () => 1;
a()
1
let b = () => { return 1; }
b()
1
a
() => 1
b
() => { return 1; }

Is there any situation when these are different?

2 Answers

One difference is that returning object literals using the implicit return syntax requires the object literal to be wrapped in parenthesis.

var foo = () => { bar: "foobar" }; //This function returns undefined
var foo = () => { return { bar: "foobar" }; }; //This function returns an object
var foo = () => ({ bar: "foobar" }); //This function returns object

As far as I'm aware, this is the only difference.

concise body arrow functions implicitly returns value whereas for multi line arrow functions you must explicitly return value.

In your case both will have same net result

Related