简体   繁体   中英

Passing in undefined as a parameter in a function (ES6)

I have a question pertaining to the usage of es6 functions that have default parameters.

Here is an example:

const add = (a = 1, b = 2) => a + b;

As you can see, a and b default to 1 and 2 respectively.

With default values, I can call the function without any parameters like so:

add(); // 3

I can also omit parameter b :

add(2); // 4

And to omit parameter a , I can pass in undefined :

add(undefined, 3); // 4

My question:

Is it bad practice to pass in undefined as a first parameter in order for the function to be called with the default first parameter, which in this instance is 1 ?

Thanks to JonathanMitchell for suggesting the object parameter.

const add = (args = {}) => {
    const a = args.a || 1;
    const b = args.b || 2;
    return a + b;
}

Examples:

add(); // 3
add({a: 2}) // 4
add({b: 3}); // 5

Edit:

loganfsmyth offered a much better solution.

using || is bad form because if you pass 0 it would also use the default.

A better and more compact solution:

const add = ({a = 1, b = 2} = {}) => a + b

Logan used ES6's deconstruction assignment (see "Default" values) to assign a and b default values in the event that such parameters evaluate to undefined .

That's usually not the best choice -- default parameters should be structured so that the second is only used if the first is also used, the third is only used if the first two are used, and so on, so you don't have the issue of passing in undefined .

There doesn't appear to be a standard way to only set a value for the second parameter, eg add({b: 5}) unless you redefine the function to take an object, so passing in undefined appears to be the only option.

MDN does that in their documentation here , see "Examples / Passing undefined".

In practice,a better option would be to create a feed dictionary to pass into the function. That way you can set which values you like and leave others as is or to another value.

feed_dict = {x: 1, y: 2}

Then you should structure a function to take in a dictionary and perform the addition on its values

const add = (dict) => {
 for (var keys in dict) {
  sum += dict[keys]
}
return sum

add(feed_dict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM