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 value greaterthan10 variable:

    var greaterthan10 = greaterthan(10); 
  • this makes function stored greaterthan10 looks 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 true result 11 > 10 true 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

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -