Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are parameters handled when passing functions in Javascript? [duplicate]

In http://eloquentjavascript.net/1st_edition/chapter6.html, there is the following example:

function negate(func) {
  return function(x) {
    return !func(x);
  };
}
var isNotNaN = negate(isNaN);
alert(isNotNaN(NaN));

Knowing only basic Javascript and imperative programming, I am stumped by this programming style. Can someone help me to understand what happens during runtime.

I stepped through the code and inspected variables and found that the value of x is NaN. How does it know that the argument to isNaN should be passed as argument x of the anonymous function? In the first place, why does the actual parameter NaN of isNotNaN become the argument to isNaN (ie while isNaN expects an argument, why does it take it from the argument of isNotNaN)?

like image 671
Old Geezer Avatar asked Sep 19 '15 15:09

Old Geezer


1 Answers

Best way to understand this might be with seeing what these things actually equal. Notice how func becomes the passed isNaN function.

function negate(func) {
  return function(x) {
    return !func(x);
  };
}
var isNotNaN = negate(isNaN);
/*

isNotNaN = function(x){
   return !isNaN(x)
}

*/

alert(isNotNaN(NaN));
like image 117
Kevin Pei Avatar answered Oct 05 '22 23:10

Kevin Pei