vitiral vitiral - 21 days ago 9
Javascript Question

named variable filter syntax in redux

I have just finished learning javascript and typescript (I know redux is not typescript), but have been thouroughly confused by the syntax for redux filters:

function visibilityFilter(state = 'SHOW_ALL', action) {
...
}


I've seem default variables in javascript, but only when the default variable is AFTER the positional variable. What is going on here? Can someone point me to documentation that explains this syntax?

Answer

Basically it means that the reducer expects to receive an action, but uses the default value if the first parameter is undefined.

function reducer(state = 'initial', action) {
  if (action.type === 'change') {
    return 'new';
  }
  
  return state;
}

console.log(
  'uses given initial state: ', 
  reducer('what', {})
);

console.log(
  'null is also considered a given state: ', 
  reducer(null, {})
);

console.log(
  'uses default state if first param is undefined: ',
  reducer(undefined, {})
); 

const myServerState = undefined;
console.log(
  'passing undefined might not be so obvious: ',
  reducer(myServerState, {})
);

// throws error because action is undefined
console.log(reducer({ type: 'change' }));

Comments