0

I have a javascript coding exercise to do which has got me a bit stuck (I'm only just starting javascript).

The exercise is as follows:

Write a function multiply(a) that returns a function capable of multiplying by a. Call this function with b as a parameter.

So far I have the main skeleton (not difficult):

function multiply(a) {
    return //Stuck here
}

I'm not sure if the question is to call multiply(b) and have it give us the result of a*b or something else...

I tried writing a function directly after the return statement but this just printed out the function name.

function multiply(a) {
    return function f { return a * b } //Here I assume b is a variable defined somewhere
}

Thanks in advance!

Max Michel
  • 575
  • 5
  • 20

1 Answers1

0

You could take a closure over the variable and return a function for the multiplication for the multiplicand.

function multiply(a) {
    return function (b) { 
        return a * b;
    }
}

var threeTimes = multiply(3);

console.log(threeTimes(7));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392