Falko
Falko

Reputation: 1035

How does the following functions return statement work

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

I'm struggling to understand how this return statement works and what the 'm' variable actually does.

Upvotes: 6

Views: 82

Answers (4)

ayushgp
ayushgp

Reputation: 5091

What you see here is known as Currying.

Currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument.

Currying is mainly a part of the functional paradigm. It is used mainly to construct functions that you can reuse later.

You can read more about currying in this SO question. As others have already mentioned, the greaterThan method returns a function which you can call in turn after you call greater than. The returned function returns a boolean based on the values you pass to it.

What the variable m actually does?

The function you have provided can be rewritten as:

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

So m is an argument to the function that is being returned. This function forms a closure on n and checks if m is greater than m and returns that value.

Upvotes: 0

Chirag Ravindra
Chirag Ravindra

Reputation: 4830

The function greaterThan accepts a parameter n and returns a new function which accepts the parameter m which in turn returns true if the argument passed as m is greater than n;

Same method in ES5 code:

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

var greaterThan5 = greaterThan(5); // This returns a function

// Call that function with a parameter to check if that is greater than 5

console.log(greaterThan5(10)); //true [n=5, m=10]
console.log(greaterThan5(1)); //false [n=5, m=1]

//Note: The newly created function will have `n` "fixed" as `5` because of how JS closures work

Handy Reference:

Javascript Closures

Arrow Functions

JS Functions (and how they are first class objects in JS)

Upvotes: 2

Jai
Jai

Reputation: 74738

That is a fat arrow syntax. The snippet follows a closure feature of javascript, where you store one value and you pass another value in it to process.

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

console.log(greaterThan(5)(10));
console.log(greaterThan(5)(1));

Upvotes: 1

Laxmikant Dange
Laxmikant Dange

Reputation: 7688

greaterThan is the function which takes a parameter n and returns a function which takes parameter m. The returned function compares m and n and returns boolean value.

for Ex:

greaterThan(5)(4); // Returns false

Upvotes: 4

Related Questions