Some languages, like Python, have named arguments that make it easy to provide defaults and put arguments in any order. JavaScript doesn’t have this sort of thing.
Modern JavaScript for the Impatient shows an interesting way to do this using object literals. The idea is that you specify your default args in a structure. That allows the function caller to override the arguments by name. If no argument value is passed in, the defaults are used.
For example,
const makePizza = ({
base = 'tomatoSauce',
cheese = 'mozzarella',
crust = 'thin'
} = {}) => {
return `${base} with ${cheese} on ${crust} crust`
}
console.log(makePizza());
console.log(makePizza({ crust: 'thick' }));
console.log(makePizza({ crust: 'thick', base: 'whiteSauce' }));
That’s a nice trick to know that is lot easier than checking each argument and then providing a default value if it is undefined
.