I understand the following codes:
function subtract(p1, p2) { return p1 - p2; }
function calculate(p1, p2, calculator) { return calculator(p1, p2); }
var result = calculate(2, 3, subtract); //-1
But I don’t understand the following codes about how p1 and p2 can be recognized as 2 and 3:
var result = calculate(2, 3, function (p1, p2) { return p1 - p2; }); //-1
UPDATE to address comment:
The reason that the anonymous function knows to use the p1 and p2 arguments is because the parameters from the calculate function definition are what is passed into the anonymous function as arguments in the body of calculate.
Perhaps a clearer way to understand what is happening here is to change the name of the parameters in the function definition of the anonymous function so that those same parameter names aren’t used in the function definition of your anonymous function. This creates a lot of confusion and is often done purposely in Computer Science textbooks when teaching about principles of programming languages and abstractions.
In addition to changing the parameter names in the anonymous function, changing the calculate parameter “calculator” to the parameter name “fn” may also help avoid confusion between calculate and calculator. Consider your function:
Function Definition:
Function call calculate, with anonymous function:
See
return fn(p1, p2);in the function definition for calculate, at the top of this answer, as a reminder of why the values assigned to p1 and p2 are passed into the anonymous function.Thus, the anonymous function returns 3 – 2 = 1.
For further reading on how this concept can create abstractions, see Joel Spolsky’s article – Can Your Programming Language Do This? Joel does a great job of explaining why JavaScript is so awesome!