I am a bit rusty on default parameters, and I am wondering how can I use a default value for a parameter if it goes before parameters without defaults?
In the example from Redux.js below, when will the default value {}
for the state
parameter be useful? (since you can't default the next parameter)?
const todo = (state = {}, action) => {
switch (action.type) {
//...
case 'TOGGLE_TODO':
if (state.id !== action.id) {
return state
}
return Object.assign({}, state, {
completed: !state.completed
})
default:
return state
}
}
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.
Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value. A default parameter can be anything from a number to another function.
The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
The usage in question is specific to redux.js
. The default value for the first parameter is generally useless in function calls because of the second parameter without default.
However, as said earlier in the same tutorial about Reducers:
Redux will call our reducer with an undefined state for the first time. This is our chance to return the initial state of our app:
function todoApp(state, action) {
if (typeof state === 'undefined') {
return initialState
}
//...
return state
}
So the 1st parameter isn't really omitted here. Redux is supplying undefined
as its value on initialization. It is only in this case, the tutorial used default arguments syntax as a shortcut:
function todoApp(state = initialState, action) {
//...
return state
}
The defaults are called when the parameter is undefined
:
todo(undefined, { type: 'WHATEVER' });
To prevent the need for setting undefined
s when calling the function, I prefer to destructure an object with defaults. Using an object make the order of the params irrelevant.
todo({ state = {}, action } = {}) => {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With