Function Overloading in JavaScript
An Overloaded Developer


        
        by 
            in CodeSOD
            on 2024-10-15
            Edit
        
        
            
            Remy PorterComputers were a mistake, which is why I'm trying to shoot them into space. Editor-in-Chief for TDWTF.
        
        
            "Oh, I see what you mean, I'll just write an overloaded function which takes the different set of parameters," said the senior dev.
That got SB's attention. You see, they were writing JavaScript, which doesn't have function overloading. "Um," SB said, "you're going to do what?"
"Function overloading," the senior dev said. "It's when you write multiple versions of the same method with different signatures-"
"I know what it is," SB said. "I'm just wondering how you're going to do that in JavaScript."
"Ah," the senior dev said with all the senior dev wisdom in the world. "It's a popular misconception that function overloading isn't allowed in JavaScript. See this?"
function addMarker(lat,lng,title,desc,pic,link,linktext,cat,icontype) {
         addMarker(lat,lng,title,desc,pic,link,linktext,cat,icontype,false);
}
               
function addMarker(lat,lng,title,desc,pic,link,linktext,cat,icontype,external) {       
    /* preparation code */
    if (external){             
        /* glue code */
    } else {
        /* other glue code */
    }
}

This, in fact, did not overload the function. This first created a version of addMarker which called itself with the wrong number of parameters. It then replaced that definition with a new one that actually did the work. That it worked at all was a delightful coincidence- when you call a JavaScript function with too few parameters, it just defaults the remainders to null, and null is falsy.


        

        
    