Javascript Developer JSE 40 01 · Free Practice Question Hard
Question 5
Q232 - Functions
Examine the following code:
- let x = mult(2)(10);
- console.log(x) // -> 20
What should the mult function declaration look like
if the execution of this code results in a value of 20 in the console?
-
A
- let mult = function(a, b) {
- return a * b;
- }
-
B
- let mult = function(a) {
- return function(b) {
- return a * b;
- }
- }
-
C
- let mult = function(a, b) {
- return b ? mult(b) : mult(a);
- }
-
D
There is an error in the code
and it is not possible to declare such a function correctly.
Reveal correct answer
Correct answer: B
Explanation
Topic: function expression nested function
Try it yourself:
- let mult1 = function(a) {
- return function(b) {
- return a * b;
- }
- }
- let x1 = mult1(2)(10);
- console.log(x1) // 20
- let mult2 = function(a, b) {
- return a * b;
- }
- // let x2 = mult2(2)(10);
- // Uncaught TypeError: mult2(...) is not a function
- console.log(mult2(2, 10)) // 20
- let mult3 = function(a, b) {
- return b ? mult3(b) : mult3(a);
- }
- // let x3 = mult3(2)(10);
- // Uncaught InternalError: too much recursion
- // console.log(mult3(2, 10))
- // Uncaught InternalError: too much recursion
Explanation:
Both not working code snippets are written to be called with two parameters:
let x = mult(2, 10);
But
let x = mult(2)(10);
is a call to a function with a nested (inner) function.
The function keyword can be used to define a function inside an expression.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function
Nested function
Q232 (Please refer to this number, if you want to write me about this question.)
A. Choice B is incorrect because the mult function is not intended to take both 'a' and 'b' as parameters in a single function call. The function needs to be structured as a curried function to enable the chaining of function calls as shown in the code snippet.
B. The correct choice is A because the mult function is defined as a higher-order function that takes an initial argument 'a' and returns another function that takes a second argument 'b'. This setup allows for partial application of arguments, resulting in the desired multiplication of 2 and 10 to produce 20 when the function is called.
C. Choice C is incorrect because the function declaration does not align with the currying pattern required for the code to function as intended. The function should be structured to return a function that can handle the second argument 'b' to achieve the desired output.
D. Choice D is incorrect as it is indeed possible to declare the mult function correctly to achieve the output of 20 in the console. By defining the function as a curried function that returns another function, the code can successfully multiply 2 and 10 to yield 20.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
