Default value settings for function parameters

There are the following functions:

function write(a,b){
console.log(a,b);
}

This function contains two parameters, namely a and b. The
calling method is as follows:
write("girl","boy");

When calling the method, if the parameter does not pass a value, it will print undefined

If we want to print a default value without passing parameters ----- "boy", that is, let the parameters have a default value.

The first thing that came to my mind was to use the ternary operator and the short-circuit operator logical OR (||)
method as follows:

function write(a,b){
b=b?b:"boy"; //b=b||"boy"
console.log(a,b);
}

 

So problem solved, let's try

No problem, try again special case empty' '
write('girl','')
Expected result: girl

Not good, the result is actually a girl boy. (I don't want to match the object for girl, the space next to it should be reserved for "me")
Forget it, let's analyze the reason, we use the ternary operator or the short-circuit operator, both of which are based on Judging by the boolean value, the boolean value corresponding to the empty string is false, so the b value here will eventually be assigned as "body"

Well, in that case. Continue to think.
If the parameter of a function does not pass a value, then the value of this parameter is not initialized, then it is "unfind" (one of the basic data types), so I can directly judge whether the parameter is passed a value. The rewritten code is as follows:

function write(a,b){
if(typeof b==='undefined'){
b='boy'
}
console.log(a,b);
}
write('girl',);

 

Continue to explore, the above method is the method that was thought of in es5 to set default parameters for functions. Although it achieves its purpose, this method still lacks a little "elegance". The code is not very readable and concise, and it is a bit troublesome to find out at a glance whether a function has a default parameter in a large block of code.
The practice of setting default parameters for functions is a relatively common scenario, so ES6 has added a new feature to solve it. The way to write a function with default parameters in ES6 is as follows:

function write(a,b='boy'){
console.log(a,b);
}
write('girl',);

 

This is much simpler, and this is the elegant implementation.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325383488&siteId=291194637