InterviewSolution
| 1. |
Write A Mul Function Which Will Produce The Following Outputs When Invoked? |
|
Answer» console.log(mul(2)(3)(4)); // output : 24 console.log(mul(4)(3)(4)); // output : 48 Below is the answer followed by an EXPLANATION to how it works: function mul (x) return function (z) Here the mul function accepts the first argument and returns an anonymous function, which takes the second parameter and returns another anonymous function that will take the third parameter and return the multiplication of the ARGUMENTS that have been passed. In JavaScript, a function defined inside another one has access to the outer function's variables. Therefore, a function is a first-class object that can be returned by other functions as well and be passed as an argument in another function.
console.log(mul(2)(3)(4)); // output : 24 console.log(mul(4)(3)(4)); // output : 48 Below is the answer followed by an explanation to how it works: function mul (x) return function (z) Here the mul function accepts the first argument and returns an anonymous function, which takes the second parameter and returns another anonymous function that will take the third parameter and return the multiplication of the arguments that have been passed. In JavaScript, a function defined inside another one has access to the outer function's variables. Therefore, a function is a first-class object that can be returned by other functions as well and be passed as an argument in another function. |
|