Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
JavaScript
    function greaterThan (n) {

    return function (m) { return m > n; };
    }

var greaterThan10 = greaterThan (10);

console .log( greaterThan10 (11) );


What I have tried:

i'm guessing:
i) var greaterThan10 assigns n a value 10.

ii) calling greaterThan10 (11) assigns m a value 11

If this is the case, how comes n is not replaced by value 11?
Posted
Updated 23-May-16 10:22am

1 solution

check this, same question answered in stack over flow [^]

In simple way,
JavaScript
function greaterThan(outer) { 
            function innerFunction(inner) { 
                return inner > outer;
            };
            return innerFunction;
        }
        console.log(greaterThan(10)(11));

greaterThan is a function which takes an input and returns a Function (innerFunction -> which takes an input and returns a bool value by comparing outer and inner arguments )
so by calling greaterThan(10), it will instantiate the function with outer value as 10 and it returns the innerFunction object which can be invoked as below. Since a Function is returned, the life time of the outer variable value (10) will be present in the inner function till the window is closed.
normally, Function is called by the syntax FunctionName(args,...)
C#
var outerFunction = greaterThan(10);
  console.log(outerFunction(11));
  // or
  console.log(greaterThan(10)(11));


to know more about function and closures refer :
JavaScript Function Closures[^]
Closures - JavaScript | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900