Javascript arrow funtions with a function as parameter [duplicate]

I was building an App in react where I found a line in one of the boiler plate projects.

(state = {}) => state

Can anyone explain to me what the above line means? It's javascript ES6 standard.


That's an arrow function with a default parameter that returns its input or an empty object, if no input was provided. It is similar to this es-5 function:

function(){
    var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
    return state;
}

It is a(n arrow) function that returns its input. If the input is not defined it will become the default value {}.

You might have seen it in combination with using redux' "connect", as the function that maps the store's state to the projection used for the connected component. If there is no state available, the empty object will be provided.


You might be more familiar with this notation:

function(state) {
    if (!state) state = {}; // state defaults to {}
    return state;
}

What you saw is ES6 syntactic sugar: function(state = {}) { ... } is a shorthand notation for default values (state defaults to {}), and (a) => b is a shorthand notation for function(a) { return b }. If you put them together, you get (state = {}) => state.