In JavaScript, what is the point of defining a function with default parameters for some arguments before other arguments without default parameters?

Kal :

I was reading the Redux documentation and something really confused me. Many, if not all, of the example reducer functions in the documentation have this kind of signature:

function visibilityFilter(state = 'SHOW_ALL', action) {
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter
    default:
      return state
  }
}

What is the point of providing a default state when the action is required anyway?

In that particular code sample, calling visibilityFilter without providing an action argument will result in a TypeError at the switch statement.

But in order to provide an action parameter, the state parameter must also be provided, and so the default value is overridden and useless. As far as I know, there is simply no way in the JavaScript syntax to call that visiblityFilter function while providing only the action parameter.

Is that just some funky/bad coding style in the world of Redux? What am I missing?

CertainPerformance :

That's some pretty strange code, but there is one case where the default parameter could be used - if undefined is explicitly passed as the first parameter:

function visibilityFilter(state = 'SHOW_ALL', action) {
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter
    default:
      return state
  }
}

console.log(visibilityFilter(undefined, {}));

(not that I would recommend writing code that looks like this in most cases)

With Redux in particular, this sort of thing can arise "naturally" because the function is a reducer, used with createStore. If createStore is passed an initial state, it'll be passed along to the reducer as the reducer's first argument; otherwise, Redux's internals will explicitly call it with an undefined first argument.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31724&siteId=1