Two sets of parentheses after function call

JavascriptAngularjs

Javascript Problem Overview


I was looking how filters works in Angularjs and I saw that we need to send 2 sets of parentheses.

$filter('number')(number[, fractionSize])

What does it means and how do we handle it with JavaScript?

Javascript Solutions


Solution 1 - Javascript

It means that the first function ($filter) returns another function and then that returned function is called immediately. For Example:

function add(x){
  return function(y){
    return x + y;
  };
}

var addTwo = add(2);

addTwo(4) === 6; // true
add(3)(4) === 7; // true

Solution 2 - Javascript

$filter('number') returns a function that accepts two arguments, the first being required (a number) and the second one being optional (the fraction size).

It's possible to immediately call the returned function:

$filter('number')('123')

Alternatively, you may keep the returned function for future use:

var numberFilter = $filter('number');

numberFilter('123')

Solution 3 - Javascript

It is the same as this:

var func = $filter('number');
func(number[, fractionSize]);

The $filter() function returns a pointer to another function.

Solution 4 - Javascript

with ES6 or later versions you can do it that way;

const divideBoth = (x) => (y) => {
   return x / y;
};

one of the reasons that makes this function type useful is when you have a react.js component that needs have callback function instead of doing it inline way(which is ()=>return value) you can do it the way we did previously. But it is not recommended to use in event callbacks because it gets execute in the first render which might cause issues sometimes

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionL105View Question on Stackoverflow
Solution 1 - JavascriptPaulView Answer on Stackoverflow
Solution 2 - JavascriptJa͢ckView Answer on Stackoverflow
Solution 3 - JavascriptBryan OakleyView Answer on Stackoverflow
Solution 4 - JavascriptÖmer AyhanView Answer on Stackoverflow