What is the best way(s) to fake function overloading in Javascript?
I know it is not possible to overload functions in Javascript as in other languages. If I neede
there is no actual overloading in JS, anyway we still can simulate method overloading in several ways:
method #1: use object
function test(x,options){
if("a" in options)doSomething();
else if("b" in options)doSomethingElse();
}
test("ok",{a:1});
test("ok",{b:"string"});
method #2: use rest (spread) parameters
function test(x,...p){
if(p[2])console.log("3 params passed"); //or if(typeof p[2]=="string")
else if (p[1])console.log("2 params passed");
else console.log("1 param passed");
}
method #3: use undefined
function test(x, y, z){
if(typeof(z)=="undefined")doSomething();
}
method #4: type checking
function test(x){
if(typeof(x)=="string")console.log("a string passed")
else ...
}