Background knowledge
In JS, you can set default values for method parameters using the following form, but only two cases are supported:
- Do not pass this parameter
- The incoming value is
undefined
const foo = (arg = 'default') => console.log(arg)
Copy the code
Other falsy values will not use default values:
Foo (" ") // "(prints an empty string, quoted for illustration) foo(null) // null foo(false) // false foo(0) // 0Copy the code
Problem scenario
Therefore, if you simply use the default values of parameters, sometimes you will encounter the problem of incorrect parameter types, such as:
// Scenario 1 const foo = (arg = () => {}) => {arg(); } foo(null) // Uncaught TypeError: arg is not a function // scene 2 const foo = (arg = {}) => {if (a.key) {// do STH... } } foo(null) // Uncaught ReferenceError: a is not definedCopy the code
The solution
During the discussion with others in the group, the following schemes were proposed:
const foo = (arg = 'default') => console.log(arg); // plan 1 axios(url, data). Then ((res) => {foo(res? .value); }) / / axios plan 2 (url, data). Then ((res) = > {foo (res) value?? "); }) / / solution 3 axios (url, data). Then ((res) = > {foo (res) value | | undefined); })Copy the code
The above scenarios avoid the previous problem scenario, but they are all from the “consumer” point of view, so that any future calls to the method will need to pass the value in one of these ways.
From the perspective of the “creator” of the method, you can use the following:
const foo = (arg) => {
arg = arg || 'default';
}
Copy the code
However, if the method itself needs to receive falsy values, you should not use this form, and you need to pay attention to the use of scenarios and decide which form to use.
If you have other better solutions, feel free to share them in the comments.