0

In a Javascript function with default parameters, is there any way to specify the arguments passed into the function call, by their name, as opposed to their order in the function definition?

function foo(a = 1, b = 2, c = 3){ console.log(a, b, c); }; foo(); // => 1 2 3 foo(5); // => 5 2 3 foo(b = 5); // => 5 2 3 

As you can see, I can change the default parameter I want, only when I insert undefined in place of the previous arguments:

foo(undefined, b = 5); // => 1 5 3 // which happens to be the same as foo(undefined, 5); // => 1 5 3 

I know that this is possible in Python:

def foo(a = 1, b = 2, c = 3): print(a, b, c) foo(b = 5) # => 1 5 3 

Is there any way to do this in Javascript without inserting undefined?

    1 Answer 1

    1

    First a good practice is to move optional parameters at the end.

    In your case you can put the optional parameters in an object specify which attribute of the object you passed like this:

    function foo({a=1, b=2, c=3} = {}){ console.log(a, b, c); }; foo(); foo({b:5})

    1
    • In this example, how would I specify one value to change and leave the others untouched? For instance, if I wanted an output of 1 5 3, how would I do it?
      – max
      CommentedAug 8, 2019 at 20:00

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.