Javascript Developer JSE 40 01 · Free Practice Question Hard

Question 5

Q232 - Functions


Examine the following code:



What should the mult function declaration look like

if the execution of this code results in a value of 20 in the console?


  • A
  • B
  • C
  • 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:


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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#nested_functions_and_closures


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.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need