1

I have a function foo defined as follows,

foo = function(a=1,b=2,c=3){ console.log("your inputs are a:" +a+", b:"+b + ", c:"+c+".") } 

How do I use the default value of b and specify a and c only when calling the function?

For example, I would like to return a console log of your inputs are a:3, b:2, c:1. when calling foo(a=3,c=1).

However, by calling foo(a=3,c=1), the console log is your inputs are a:3, b:1, c:3.. The JavaScript thinks the c=1 should be the value of the second parameter b and the third parameter c is not given and will use its default value of 3. In addition, by calling this function, the object of a and c are also created.

1
  • The only thing you can do is leave off parameters at the end of the list; you can't omit a parameter in the middle. edit or do the object destructuring as suggested.
    – Pointy
    CommentedJun 19, 2019 at 22:29

1 Answer 1

3

I'd pass an object instead, and destructure the arguments:

function foo ({ a=1,b=2,c=3 }){ console.log("your inputs are a:" +a+", b:"+b + ", c:"+c+".") } foo({ a: 99, c: 99 });

In case the function may be called without any parameter, assign the default parameter to {} too:

function foo ({ a=1,b=2,c=3 } = {}){ console.log("your inputs are a:" +a+", b:"+b + ", c:"+c+".") } foo();

You can also explicitly pass undefined for missing arguments:

function foo (a=1,b=2,c=3){ console.log("your inputs are a:" +a+", b:"+b + ", c:"+c+".") } foo(99, undefined, 99);

4
  • I love your 1st and 2nd way. Interesting how the javascript can capture the unspecified parameter and find its default value. Though I still do not completely understand the mechanisms here. I just wanted to avoid using the 3rd way especially when there are a lot of parameters (with default values) in the function.
    – WCMC
    CommentedJun 19, 2019 at 22:35
  • 1
    When there are lots of parameters, having multiple standalone parameters probably isn't a good idea, because you have to carefully keep in mind which order the parameters are supposed to be in - I'd prefer the object destructuring method regardless, when there are many "parameters", just for the sake of readability, even without the issue of default values.CommentedJun 19, 2019 at 22:38
  • Should 'foo(99, undefined, 99);' be 'foo({99, undefined, 99});'? Or, since you are using all three parameters you don't need the {}?
    – CharlesEF
    CommentedJun 19, 2019 at 22:53
  • When the function accepts multiple standalone parameters, you need to pass undefined to fill the "holes" in the parameters. When the function accepts a single object, the (attempted) destructured property will be undefined regardless, so specifying the missing parameters is unnecessary (as you can see by pressing "Run code snippet" in the answer)CommentedJun 19, 2019 at 23:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.