Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function with a specific default argument in JavaScript?

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?

like image 213
Jurij Avatar asked Mar 23 '26 11:03

Jurij


1 Answers

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)

like image 191
Nathan Chappell Avatar answered Mar 26 '26 10:03

Nathan Chappell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!