Atul Mishra
Atul Mishra

Reputation: 43

How to call a function and its child function in JavaScript?

I am learning JavaScript, so if this question is nonsense correct me.

function greaterThan(n) { 
return m => m > n;
} 
let greaterThan10 = greaterThan(10); 
console.log(greaterThan10(11)); 
        // → true

In this function is there is any possible way to call inside function m=> m > n along with " greaterthan " function ? Like greaterthan(10(11)); 🤔 where I provide m and n both variables ?

Upvotes: 1

Views: 68

Answers (2)

Muhammad Usman
Muhammad Usman

Reputation: 10148

This is how you do that

greaterThan(10)(11);

As greaterThan(n) returns a function, so you are just calling that function passing some parameters

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

console.log(greaterThan(10)(11)); 

There is a way to reduce functions of more than one argument to functions of one argument, a way called currying

Here is an interesting blog to read about currying

Upvotes: 2

Matus Dubrava
Matus Dubrava

Reputation: 14462

That function is curried, meaning that it takes one argument at a time and returns new, partially applied function until all the arguments were provided. If you want to execute such function while passing all the arguments at once, then you need to uncurry it first.

For that, you need either some library that provides uncurry function or you can write your own.

function uncurry(f) {
  if (typeof f != "function" || f.length == 0) { return f; }
  return function() {
    var r = f;
    for (var i = 0; i < arguments.length; i++) { r = r(arguments[i]); }
    return r;
  };
}

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

const greaterThanUnc = uncurry(greaterThan);
console.log(greaterThanUnc(10, 11));

Upvotes: 0

Related Questions