3

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?

4
  • The name of the parameter dosn't matter, only the position matters. Commented Jun 18, 2020 at 3:17
  • Try this: foo(0, undefined , 10); Commented Jun 18, 2020 at 3:20
  • So there is no way of doing that (apart from passing parameters as a json)? This works in python. So, I assumed javascript would also have a similar feature. Commented Jun 18, 2020 at 3:21
  • as mentioned by @SoluableNonagon, you can pass object, as long as the func. signature allows it, and use destructuring. Commented Jun 18, 2020 at 6:07

1 Answer 1

7

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 }) )

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.