I'm trying to create a function that has multiple optional arguments. I am then trying to only assign the second argument without having to also assign the first one.
function foo(bar, zar) {
bar = bar || 5;
zar = zar || 2;
return bar * zar;
}
foo() //10
foo(7) //14
foo(7, 3) //21
foo(zar=5) //10 <-- why is this not 25?
What is the best way to do this?
Use
void 0
instead of the arguments you don't want to supply.For example:
foo(void 0,zar=5);
Any unfilled argument will be
undefined
.You cannot pass the second parameter without passing the first, but you can pass
undefined
. In the function, you can check forundefine
d and replace with a default value.Alternately, you can use an object argument to imitate keyword arguments.