01 const addBy = ?
02 const addByEight = addBy(8);
03 const sum = addByEight(50);
Which two functions can replace line 01 and return 58 to sum?
Show answerHide answer
Correct answer: A, D
const addBy = function(num1) {
return function(num2) {
return num1 + num2;
}
}(Corrected for typing errors)
const addBy = (num1) = > {
return function(num2) {
return num1 + num2;
}
}
Explanation
Explanation:This question tests understanding of closures and higher-order functions in JavaScript. The code pattern shows addBy being called with 8 (returning a function), then that returned function is called with 50 to produce 58. This requires addBy to be a function that returns another function which captures the first argument (num1) and adds it to the second argument (num2) when invoked.
Correct Options:
A – Correct.
This defines addBy as a function that takes num1 and returns a new function that takes num2 and returns num1 + num2. When addBy(8) is called, it returns function(num2) { return 8 + num2; }. Then addByEight(50) adds 8 + 50 = 58. This is a proper closure implementation.
D – Correct.
This is the arrow function equivalent of option A. addBy is defined as an arrow function that takes num1 and returns an inner function (using traditional function syntax) that takes num2 and returns num1 + num2. It works identically to option A, creating a closure that captures num1 and returns 58 when called with 50.
Incorrect Options:
B – Incorrect.
This function takes only one parameter num1 but tries to use num2 which is not defined in its scope. This would throw a ReferenceError because num2 is not accessible. Additionally, it doesn't return a function as required by the pattern.
C – Incorrect.
This arrow function (num1) => num1 + num2 also tries to reference num2 which is not defined in its scope. It would throw a ReferenceError. Moreover, it doesn't return a function, so addBy(8) would return a number (or error), not a function that can be called with 50.
Reference:
MDN Web Docs - Closures and Function returning functions; Salesforce LWC JavaScript documentation on higher-order functions and closures.