Search code examples
ecmascript-6default

Why react-redux connect() give a default value like this?


I just wonder why does it give a "={}" which is a empty default value after initializing the parameters of the function given below, Can anybody answer this?

return function connect(
mapStateToProps,
mapDispatchToProps,
mergeProps,
{
  pure = true,
  areStatesEqual = strictEqual,
  areOwnPropsEqual = shallowEqual,
  areStatePropsEqual = shallowEqual,
  areMergedPropsEqual = shallowEqual,
  ...extraOptions
} = {} ){ // code is here }

Solution

  • You can set defaults for the parameters of the object, and for the destructured properties. The ={} is the default for the function parameter you want to destructure. If you won't define this default, and the caller of the method won't supply an object, the call will fail with an error:

    const demo = ({ a = 1, b = 2 }) => ({ a, b });
    
    console.log(demo({})); // works fine because it tries to destructure an object
    
    console.log(demo()); // fails because the destructuring target is undefined

    If you set the default value ={} it can handle undefined values as well:

    const demo = ({ a = 1, b = 2 } = {}) => ({ a, b });
    
    console.log(demo()); // works because it has a default value