Function Overloading in JavaScript

Last Updated : 18 Sep, 2024

Function Overloading is a feature found in many object-oriented programming languages, where multiple functions can share the same name but differ in the number or type of parameters. While languages like C++ and Java natively support function overloading, JavaScript does not support this feature directly.

In JavaScript, if two or more functions share the same name, the last defined function will overwrite the previous ones. This is because JavaScript treats functions as objects, and a subsequent function with the same name simply reassigns the function reference.

Unlike other programming languages, JavaScript Does not support Function Overloading.

Example: Here is a small code that shows that JavaScript does not support Function Overloading. 

JavaScript
function foo(arg1) {
    console.log(arg1);
}

/* The above function will be
   overwritten by the function 
   below, and the below function 
   will be executed for any number
   and any type of arguments */
function foo(arg1, arg2) {
    console.log(arg1, arg2);
}

// Driver code
foo("Geeks")

Output
Geeks undefined

Explanation:

  • JavaScript does not natively support function overloading.
  • In the above example, the second function foo(arg1, arg2) overwrites the first function foo(arg1). When you call foo("Geeks"), the function with two parameters is called, but the second argument remains undefined because only one argument was passed.

We have seen that function Overloading is not supported in JavaScript, but we can implement the function Overloading on our own, which is pretty much complex when it comes to more numbers and more types of arguments. 

Example: The following code will help you to understand how to implement the function Overloading in JavaScript. 

JavaScript
// Creating a class  "foo"
class foo {

    // Creating an overloadable method/function.
    overloadableFunction() {

        // Define three overloaded functions
        let function1 = function (arg1) {
            console.log("Function1 called with"
                    + " arguments : " + arg1);
            return arg1;
        };

        let function2 = function (arg1, arg2) {
            console.log("Function2 called with"
                    + " arguments : " + arg1 
                    + " and " + arg2);
            return arg1 + arg2;
        };

        let function3 = function (arg1) {
            let concatenated__arguments = " ", temp = " "

            // Concatenating all the arguments 
            // and storing them into a string
            for (let i =