Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript invoking a function in different ways

  1. What is difference / similarities between calling a function like the following ?
  2. What is the purpose of having these two ways?
  3. What are their pros and cons?
  4. Can someone explain how this call works -> sum(2)(3); ? And mention other conventional equivalent of this call ?

The sum function for both this call can be created like the following code

function sum(x) {
  if (arguments.length == 2) {
    return arguments[0] + arguments[1];
  } else {
    return function(y) { return x + y; };
  }
}

console.log(sum(2,3));   // Outputs 5
console.log(sum(2)(3));  // Outputs 5
like image 386
Sethu Nagappan Avatar asked Oct 10 '17 00:10

Sethu Nagappan


2 Answers

Depends on the context, both methods are equally important, though I would guess that the latter form is used less. When to use one over the other? Simple, if you need to pass arguments that are immediately accessible, use the first form. If one of the arguments does not change and the caller expects a function, use the second form. Consider this code, I believe it clearly illustrates my point:

function add_direct(a, b) {
    return a + b;
}

function add_functor(a) {
    return function (b) {
        return a + b;
    }
}

var nums = [1,4,8];

var add3 = add_functor(3);

console.log(nums.map(add3));

console.log(nums.map(n => {
    return add_direct(3, n);
}));

They both add 3, but the second form makes sense here. Both have their strengths and weaknesses. Hopefully, this clears up the air.

PS: In C++, the second form is called a Functor; Others call them closures or Function objects.

like image 75
Rafael Avatar answered Sep 24 '22 16:09

Rafael


  • 1 and 2: Both achieve the same thing. The difference is that you can use the latter to reduce code size if and when is applicable.
  • 3: Execution speed may vary. For example array mapping is slower than functor if we use an edge case of Rafael's example above.

Huge array - Edge case Functor vs Function

  • 4: Discussion on functors usually gets formal and theoretical. The reason for this is that, like all functional programming techniques, functors originate from mathematics, in this case category theory. Functors are defined as: “morphisms between categories” i.e a functor is an entity that defines the behavior of "fmap" that, given a value and function "morphism", maps said function onto a value of certain type "category" and generates a new functor. So an array is a Functor, because the array can be mapped over.

Simply put, a functor is a value (an object in javascript) that:

  1. Has a map method that expects a function
  2. The expected function can return any kind of value
  3. The map function will return another functor of the same type (as the original functor)

You can find some basic examples here and here.

like image 45
Panos Kal. Avatar answered Sep 21 '22 16:09

Panos Kal.