How to Overload Function in JavaScript

Mehvish Ashiq Feb 02, 2024
  1. Use the if-else Statement to Do Function Overloading in JavaScript
  2. Use the switch Statement to Do Function Overloading in JavaScript
  3. Use Function Expressions to Do Function Overloading in JavaScript
How to Overload Function in JavaScript

This tutorial educates you about JavaScript function overloading. Function overloading means having more than one function with the same name and various implementations. But, this concept is not available in JavaScript.

If you have multiple functions with the same name, the last function is executed in JavaScript. So, we use alternatives to implement function overloading in JavaScript.

This tutorial uses if-else, switch, and function expressions to accomplish the function overloading.

Use the if-else Statement to Do Function Overloading in JavaScript

function displaySum() {
  // if no argument
  if (arguments.length == 0) {
    console.log('No argument is passed.');
  }

  // if only one argument
  else if (arguments.length == 1) {
    console.log('You have to pass at least two arugments to perform addition.');
  }

  // multiple arguments
  else {
    let sum = 0;
    let length = arguments.length;
    for (var i = 0; i < length; i++) {
      sum = sum + arguments[i];
    }
    console.log('Sum is ' + sum);
  }
}

displaySum();                     // call function with no parameter
displaySum(3);                    // call function with one parameter
displaySum(4, 5);                 // call function with two parameters
displaySum(3, 5, 7, 2, 9, 7, 8);  // call function with multiple parameters

Output:

"No argument is passed."
"You have to pass at least two arguments to perform addition."
"Sum is 9"
"Sum is 41"

In the code snippet, we use the if-else statement to do function overloading in JavaScript. We call the displaySum() function that performs differently with different parameters. It displays a message if no or one parameter is passed.

It adds the two numbers if two parameters are given and uses a for loop to add all values in multiple parameters. The arguments are array-like objects that play a vital role and can be used within the function. It represents the arguments passed of that particular function in which it is being used.

Use the switch Statement to Do Function Overloading in JavaScript

We can also implement the function overloading in JavaScript by using the switch statement instead of the if-else statement. Although both are producing the same output, the code looks cleaner with the switch statement.

function displaySum() {
  switch (arguments.length) {
    // if no argument
    case 0:
      console.log('No argument is passed.');
      break;

      // if only one argument
    case 1:
      console.log(
          'You have to pass at least two arguments to perform addition.');
      break;

      // multiple arguments
    default:
      let sum = 0;
      let length = arguments.length;

      for (var i = 0; i < length; i++) {
        sum = sum + arguments[i];
      }
      console.log('Sum is ' + sum);
      break;
  }
}

displaySum();                     // call function with no parameter
displaySum(3);                    // call function with one parameter
displaySum(4, 5);                 // call function with two parameters
displaySum(3, 5, 7, 2, 9, 7, 8);  // call function with multiple parameters

Output:

"No argument is passed."
"You have to pass at least two arguments to perform addition."
"Sum is 9"
"Sum is 41"

In this code, we use the switch statement to accomplish different actions based on various arguments. You can read about the arguments object here or in the previous section.

Use Function Expressions to Do Function Overloading in JavaScript

// Creating a class "practiceFunctionOverloading"
class practiceFunctionOverloading {
  // Creating an overloadable function.
  displaySum() {
    // Define four overloaded functions
    var functionNoParam = function() {
      return 'No parameter is passed.';
    };
    var functionOneParam = function(arg1) {
      return 'You must have at least two parameters to sum.';
    };
    var functionTwoParam = function(arg1, arg2) {
      console.log('Sum is given below: ');
      return arg1 + arg2;
    };
    var functionMultiParam = function(arg1, arg2, arg3) {
      var sum = 0;
      for (var i = 0; i < arguments.length; i++) {
        sum = sum + arguments[i];
      }
      console.log('Sum is given below: ');
      return sum;
    };

    /* the length and type of the arguments passed
       ( in this case an Array ) we can determine
       which function to be executed */
    if (arguments.length === 0) {
      return functionNoParam();
    } else if (arguments.length === 1) {
      return functionOneParam(arguments[0]);
    } else if (arguments.length === 2) {
      return functionTwoParam(arguments[0], arguments[1]);
    } else if (arguments.length > 2) {
      return functionMultiParam(arguments[0], arguments[1], arguments[2]);
    }
  }
}
// Driver Code
// create an object of class practiceFunctionOverloading
var object = new practiceFunctionOverloading();
console.log(object.displaySum());         // call function with no parameter
console.log(object.displaySum(1));        // call function with one parameter
console.log(object.displaySum(2, 3));     // call function with two parameters
console.log(object.displaySum(2, 4, 5));  // call function with three parameters

Output:

"No parameter is passed."
"You must have at least two parameters to sum."
"Sum is given below: "
5
"Sum is given below: "
11

We use function and function expression to simulate function overloading using JavaScript. The disadvantage of this approach is that the code looks messier if hundreds of parameters are passed.

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript Function