Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript two brackets after function name

What does below syntax means?

connect(mapStateToProps, mapDispatchToProps)(Home)

I understand we are passing two arguments to a function, but what is the purpose of below one?

(Home) 
like image 696
ManMohan Vyas Avatar asked Jan 25 '18 12:01

ManMohan Vyas


2 Answers

It doesn't look like node but Redux and as in a comment not an ES6 thing.

What it is: Connect is a higher order (factory) function ie. it returns a function. And it is that returned function which is immediately called with Home

Take a look and an example of mock of connect below

function connect(param1, param2) {
    return innerFunction (innerParam) {
       console.log(`${param1} ${innerParam} ${param2}`) 
    }
}

connect('A','B')('precedes')

// outputs 'A precedes B'

Edit: Added an example.

like image 68
Mieszko Avatar answered Oct 13 '22 23:10

Mieszko


A function can return a function, and you can call this returned function immediately.

For information and as already stated in comments, the fact of decomposing one function call into smaller like this one in your example is called currying and is a common practice in JavaScript (more info here : What is 'Currying'?)

This example might help you :

function function1(info) {
    return function(innerParam) {
        console.log(`Hello this function has info ${info} and has just been called with this param: ${innerParam}` )
    }
}

function1('Bobby')('Alice');

// same as :
var bobbyFunction = function1('Bobby');
bobbyFunction('Alice');

This is useful to dynamically generate a function that depends on some parameter, but can still be called several time with some other changing parameters. Imagine this, for instance :

var bobbyFunction = function1('Bobby');
['Alice', 'Tommy', 'Johny'].forEach(name => bobbyFunction(name));
like image 22
Pac0 Avatar answered Oct 13 '22 23:10

Pac0