How does this "higher-order functions" thing works in Javascript -
from book eloquent javascript marijn haverbeke, there this example while introducing concept of higher-order functions:
function greaterthan(n) { return function(m) { return m > n; }; } var greaterthan10 = greaterthan(10); console.log(greaterthan10(11)); // → true i'm not quite sure how works... answering own question, how see it:
first,
greaterthan(n)called in line, assigning valuegreaterthan10variable:var greaterthan10 = greaterthan(10);this makes function stored
greaterthan10looks like:function greaterthan(10) { return function(m) { return m > 10; }; }then, when call
greaterthan10(11)calling function above, translates to:function greaterthan(10) { return function(11) { return 11 > 10; }; }hence returning
trueresult11 > 10true indeed.
could confirm whether i'm correct or not? also, if can provide further details , comments on how higher-order functions work in javascript, appreciated.
you're correct, level of understanding, it's evaluated differently.
var greaterthan10 = greaterthan(10); this line doesn't make function stored greaterthan10 "look like" - creates new function, passing in variable n it, greaterthan10 becomes function looks like
var greaterthan10 = function(m) { return m > 10; }; when call it, calling function directly, not going through original function @ anymore.
Comments
Post a Comment