0

My javascript code works with arrow function but not with normal function

//NORMAL FUNCTION (not working)
function multiplier(factor) {
    return function (number) {
        number * factor;
    }
}
const twice = multiplier(2);
console.log(twice(5));


//ARROW FUNCTION (working)
function multiplier(factor) {
    return number => number * factor;
}
const twice = multiplier(2);
console.log(twice(5));

Thanks

  • 2
    You need to return result in `return function (number) {` and with arrow function without curly braces result is returned automatically. – Nick Surmanidze Sep 11 '20 at 07:53
  • See: https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable – T.J. Crowder Sep 11 '20 at 07:55

1 Answers1

4

You're missing a return statement in the inner function

function multiplier(factor) {
    return function (number) {
        return number * factor;
    }
}
famenev
  • 256
  • 2
  • 3
  • So the return before the normal function is not doing anything? – Hamza Masood Sep 11 '20 at 07:58
  • Nice catch! After the fix, `multiplier(2)(5)` can be used – iAmOren Sep 11 '20 at 07:58
  • 1
    @HamzaMasood it does, it returns the inner function. If you use an arrow function without braces it just returns automatically. You can also write it as a double arrow function `const multiplier = (factor) => (number) => factor * number`, then you don't need the return statement on the outer function – famenev Sep 11 '20 at 08:10