I am learning JavaScript and using the Eloquent JavaScript book by Marijn Haverbeke. I don't understand how the below higher order function works, specifically how the variables m and n are assigned.
Please advise.
function greaterThan(n) {
return m => m > n;
}
let greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
// → true
I've run the code and proven that it works for when m > n (true) and when m < n (false).
CodePudding user response:
First of all, there are multiple concepts you need to understand:
Function declaration is a description of what function accepts and how does it behave. In your example
function greaterThan(n) { ... }andm => ...are function declarations.Function invocation is a request to execute specific function with specific arguments. In you example
greaterThan(10)is a function invocation.Parameters are special local variables that a function accepts and can use later. In your example,
nis a parameter ofgreaterThanfunction andmis a parameter of the inner function.Arguments are specific values of parameters passed during function invocation.
Function scope is tougher to explain. It kind of a virtual space containing references to all the variables visible in specific function. For example,
greaterThansees variablenonly, but innerm => m > nsees bothnandm. That's because of another concept called closure.Closure - tldr means that inner function can reference variables from all parent scopes, up to global scope.
Now to explaining your case.
function greaterThan(n) {
return m => m > n;
}
This declares a function greaterThan with a single parameter n.
This function returns a closure - anonymous function with single parameter m.
let greaterThan10 = greaterThan(10);
This invokes greaterThan function with 10 as argument. greaterThan returns a closure with n=10. E.g:
let greaterThan10 = m => m > 10;
And finally
console.log(greaterThan10(11));
invokes the function returned by greaterThan with 11 as an argument.
E.g. (m => m > 10)(11) -> 11 > 10 -> true.
I hope this is helpful.
CodePudding user response:
The variable n is the parameter to greaterThan(), so it's assigned when that function is called. The function returns another function, one with a parameter called m. That parameter is assigned a value when the returned function is called.
Thus in your example, n gets the value 10 when greaterThan() is called, and then m in the returned function gets the value 11 when that function is called.
