1
function demo(a,b,c,d=1,e=2,f=3){
    console.log(a,b,c,d,e,f); //prints all passed parameters
}

demo(1,2,3,e=5); //calls demo function with the parameter 'e' set to 5

//expected output: 1 2 3 1 5 3

//real output: 1 2 3 5 2 3

msba
  • 141
  • 1
  • 8
  • JS doesn't have named arguments. You can't skip over arguments like you can in Python. – Barmar Mar 22 '23 at 19:17
  • The usual solution for this is for the function to take all the options in a single object parameter. You can then merge the parameter with an object containing defaults. – Barmar Mar 22 '23 at 19:18
  • Does this answer your question? [Is there a way to provide named parameters in a function call in JavaScript?](https://stackoverflow.com/questions/11796093/is-there-a-way-to-provide-named-parameters-in-a-function-call-in-javascript) – kelsny Mar 22 '23 at 19:18
  • I read that post before I posted my question. The answer by Nina Scholz is the perfect answer for me :) – msba Mar 22 '23 at 20:07

1 Answers1

3

You need to use the right parameter slot for handing over a value, like

function demo(a, b, c, d = 1, e = 2, f = 3) {
    console.log(a, b, c, d, e, f);
}

demo(1, 2, 3, undefined, 5);

Another solution could be an object, like

function demo({ a, b, c, d = 1, e = 2, f = 3 }) {
    console.log(a, b, c, d, e, f);
}

demo({ a: 1, b: 2, c: 3, e: 5 });
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392