Practical Examples

Now it’s time to see what the image/banner above depicts in code:-

const sum = x => y => x + y;
sum (2)(1); // returns the number 3
sum (2); // returns a function y => 2 + y

And now an example for folks who are still used to ES5 syntax.

var sum = function sum(x) {
  return function (y) {
    return x + y;
  };
};

Note that sum (2)(1); produces the same result that we would get if we had defined it as const sum = (x,y) => x + y; which we would call as
sum (2, 1);.

The above code will work perfectly fine as JavaScript has first-class functions.

First-class functions

A programming language is said to have first-class functions when functions in that language are treated like any other variable. For example, a function can be passed as an argument to other functions, can be returned by another function, and can be assigned as a value to a variable.

Discussion

3

0