JavaScript Function Overloading

function-overloading-js

Before understanding JavaScript function overloading we need to understand function overloading. Function overloading is an elegant concept of object-oriented programming language. According to this concept, we can create the same name function with different arguments. Let’s take an example of the C++ language –


// Same function name different arguments
int sum() {}
int sum(int no) {}
float sum(double no) { }
int test(int no1, double no2) { }

You can see all functions have the same name but their arguments are different. Now understand how function overloading works in the C++ language.


#include <iostream>
#include <cmath>

using namespace std;

int area(int w, int h) {
  return w * h;
}

double area(int r) {
  return M_PI * pow(r, 2);
}

int main() {
  int rect = area(8, 5);
  double circle = area(2);
  cout << "Area of Rectangle: " << rect << "\n";
  cout << "Area of Circle: " << circle;
  return 0;
}

//Area of Rectangle: 40
//Area of Circle: 12.5664

Here you can see we have an area function that calculates the area of square and circle. Here, we can easily call and get the area of both shapes.

But somehow in javascript, we can’t use this concept and also javascript function do not require any return type. But Somewhere we need code more readable so we require this type of arrangments. For that, we have some techniques by which we can achieve this easily.


function getName(firstname, lastname) {
	if (arguments.length == 1) {
		return "Hello, Mr. " + firstname;
	} else if (arguments.length == 2) {
		return "Hello, Mr. " + firstname + " " + lastname;
	}
}
console.log(getName("John"));  // Hello, Mr. John
console.log(getName("John", "Resig")); // Hello, Mr. John Resig

The second technique is using object passing.


funcion getName(opration, firstname, lastname) {
	switch(opration) {
		case "FirstName":
			return "Hello, Mr. " + firstname;
		case "FullName":
			return "Hello, Mr. " + firstname + " " + lastname;
		default:
			return "Please provide operation";
	}
}

console.log(getName());  // Please provide operation
console.log(getName("FirstName", "John"));  // Hello, Mr. John
console.log(getName("FullName", "John", "Resig")); // Hello, Mr. John Resig

The third technique is using object passing.


function area(args) {
	if (args["op"] == "rect") {
		return args["w"] * args["h"];
	} else if (args["op"] == "circle") {
		return Math.PI * Math.pow(args["r"], 2);	
	}
}

console.log(area({"op":  "rect", w: 8, h: 5}));  // 40
console.log(area({"op":  "circle", r: 2}) ); // 12.566370614359172

You May Also Like

About the Author: Pankaj Bisht