Well, it's hardly what you'd call overloading, but what you're trying to do is allowed:
function f(a,b)
{
if (b === undefined)//or typeof b === 'undefined'
{
console.log('Only param a was passed to me');
return;//end function
}
console.log('Both params were passed');
}
Of course, now if I were to call f
with b
set to undefined explicitly, the code above won't pick up on that. That's where the arguments
object comes in:
function f(a,b)
{
if (b === undefined && arguments.lenght < 2)//or typeof b === 'undefined'
{
console.log('Only param a was passed to me');
return;//end function
}
b = b || 'default value';//fix possibly undefined value
console.log('Both params were passed');
}
Alternatively, you could use a single argument all the time, and treat it as an object literal:
function f(o)
{
o = o || {a: 'foo', b: 'bar'};//default object literal
var a = o.a || 'default a',
b = o.b || 'default b';
}
You've got tons of options to choose from, I'd say