3

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?

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • 8
    Yes they are the same. – Felix Kling Sep 20 '17 at 16:24
  • 1
    with {} you can make body multiline, no other difference – juvian Sep 20 '17 at 16:26
  • Related: [Arrow function without curly braces](https://stackoverflow.com/questions/39629962/arrow-function-without-curly-braces), [Curly Brackets in Arrow Functions](https://stackoverflow.com/questions/35440265/curly-brackets-in-arrow-functions), [ES6 Arrow function with brackets](https://stackoverflow.com/questions/38730747/es6-arrow-function-with-brackets) – trincot Sep 20 '17 at 16:30
  • @juvian you mean multi-statement. Multi-line is always possible even in a single expression. – Bergi Sep 20 '17 at 17:28
  • @Bergi yeah true – juvian Sep 20 '17 at 17:33

2 Answers2

5

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.

Jonah
  • 1,495
  • 4
  • 17
  • 32
  • wonder if this is why i was going through something... during a filter method... this didn't work: .filter (x => { x == 'a' }) BUT this DID work .filter(x => x=='a'). Does this have to do with what you said ? – carinlynchin Jan 23 '18 at 04:21
2

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

alt255
  • 3,396
  • 2
  • 14
  • 20
  • Before you answer, please get your terminology straight. The term "fat arrow" has not been used for several years. Also, it is not a "single line"; it is a "concise body". –  Sep 20 '17 at 16:44
  • @torazaburo how do you know the term "fat arrow" has not been used for several years? do you have any metrics? same for "single line" – alt255 Sep 20 '17 at 18:17
  • It's hard to prove a negative. Please look for references to the term "fat arrow" in the spec, or on MDN. The technical term for the non-`{}` form is perfectly clear: it is "concise body". A concise body could be multiple lines, as in `() => 1 + (NEWLINE) 2`. –  Sep 20 '17 at 19:04