Passing values to function with multiple default parameters

Viewed 779

Consider a function with 3 (arbitrary) parameters, two of which have a default value:

const foo = (a, b=1, c=2) => {
    console.log(a,b,c);
}

Now, I want parameter b to have its default value, and parameter c to have the value passed by me. I did something like this:

foo(0, c = 10); // Ideally, a = 0, b = 1, c = 10

But the output of the function is:

0 10 2

So, the value of 10 is being passed into parameter b instead of c. Why is this happening even after I have explicitly passed the value of c? What is the correct way to achieve what I want to do?

1 Answers

You need to pass undefined as a parameter for a default to take.

const foo = (a, b=1, c=2) => {
    console.log(a,b,c);
}

console.log(foo(1))

console.log(foo(1, undefined,25))

For the kind of signature you're trying to pass consider always passing an object and destructuring

    const foo = ({ a, b=1, c=2 }) => {
        console.log(a,b,c);
    }

    console.log( foo({ a: 1 }) )

    console.log( foo({ a: 2, c: 5 }) )

Related