3

So I have a function like so:

function foo(a, b, c=0, d=10, e=false) {
  // ...
}

I would like to call this function with specific inputs, but not necessarily need to list them in order in the input. So like:

foo("bar", "skurr", e=true);

I know in python you can call functions this way, but it seems there is another method I am unaware of for js.

I have tried inputting an object but that did not work since it just uses the object as the first parameter of the function.

foo({a: "bar", b: "skurr", e: true});

How do I call functions in this manner in JavaScript?

Jurij
  • 145
  • 1
  • 1
  • 8

2 Answers2

2

One option uses the "object as first argument" as you've described, but the syntax is a bit odd. Consider:

function foo({a, b=0}) { console.log(a,b); }

This defines a function which requires an object as a first argument, and imposes structural constraints on that object. In particular, the following will work:

foo({a:1});            // output: 1 0
foo({a:1, b:2});       // output: 1 2
foo({});               // output: undefined 0
foo({a:1, b:2, c: 3}); // output: 1 2 /* c is ignored */

While the following will throw an error:

foo(); // TypeError: Cannot destructure property `a` of 'undefined' or 'null'

Another option, which is something you see a lot, is an idiom of the form:

function foo(some_object) { let {a,b} = some_object; console.log(a,b); }

Both of these are instances of destructuring. As far as I know it's the closest you'll get to python-like syntax (this answer gives perhaps some more exposition and I give a perhaps too thorough analysis of the formal language which explains the observed effects ES6 destructuring object assignment function parameter default value)

Nathan Chappell
  • 2,099
  • 18
  • 21
0

You can specify undefined for the values you want to default. This works because omitted values are also undefined. In your case, this would be:

function foo(a, b, c = 0, d = 10, e = false) {
  // ...
}

// call:
foo("bar", "skurr", undefined, undefined, true);

Note that the above example is bad practice. If you have more than a few parameters (arguments), you should consider using objects and destructuring instead:

function foo({a, b, c = 0, d = 10, e = false} = {}) {
  // ...
}

// call:
foo({a: "bar", b: "skurr", e: true});
ADTC
  • 8,999
  • 5
  • 68
  • 93