-1

So to my understanding which is obviously wrong at this moment in time is that,

return arg => arg*2

is the same as

return (arg)=>{arg*2}

I always assumed arrow functions are just syntactically neater.

But doing this with closures like so doesn't work.

function addTwoDigits(firstDigit){
    return (secondDigit)=>{firstDigit + secondDigit}
}
let closure = addTwoDigits(5);
console.log(closure(5)) // Undefined

Yet this is fine

function addTwoDigitsV2(firstDigit){
    return secondDigit => firstDigit + secondDigit
}
let closure2 = addTwoDigitsV2(10);
console.log(closure2(10))// 20
Matt Way
  • 32,319
  • 10
  • 79
  • 85
Munerz
  • 1,052
  • 1
  • 13
  • 26
  • Thanks for all the answers, I'll mark this question as answered when the time limit has subsided appreciate the help. – Munerz Aug 17 '18 at 19:30
  • 1
    The word closure is a bit of red herring in this question as the problem doesn't have anything to do with closures, but is a syntax issue. – Resonance Oct 06 '20 at 15:09

4 Answers4

6

arrow function works differently here:-

(x)=> x*2 ; // dont have to return anything, x*2 will be returned
is not same as 
(x) =>{x*2}
//here you need to return something otherwise undefined will be returned
Atul
  • 420
  • 2
  • 10
  • Can't see the correct terminology here anywhere, so I thought I'd chuck in that the first example is an example of _implicit return_, which arrow functions support. – onefootswill Dec 22 '18 at 01:58
5

When you use {} you must set return

return (arg)=>{return arg*2}
mariamelior
  • 91
  • 1
  • 7
3

The arrow function only supplies the return automatically if you have an expression after the arrow. If the arrow is followed by a curly brace, it's treated as the braces around a function body, so you have to write return explicitly, i.e.

arg => arg * 2

is equivalent to:

(arg) => { return arg * 2; }

function addTwoDigits(firstDigit) {
  return (secondDigit) => {
    return firstDigit + secondDigit
  }
}
let closure = addTwoDigits(5);
console.log(closure(5))
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You need a return statement if the body of your arrow function is wrapped in { ... }.

Since yours is a single expression, you can skip the {-} and return. But if you have the {-}, you need the return statement.

The parentheses are not an issue here. You need them if you have more than a single parameter. With one, they're optional.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103