Function Overloading In JavaScript
JavaScript does not support the function overloading. Because we can pass the any number of arguments to the function and JavaScript will create the array of that arguments called the arguments.
If you think that you can create the function overloading concept in the JavaScript like this:
function add(num1, num2) { document.write("add with 2 arguments: " + (num1 + num2)); } function add(num1, num2, num3) { document.write("add with 3 arguments: " + (num1 + num2 + num3)); } function add(num1, num2, num3, num4) { document.write("add with 4 arguments: " + (num1 + num2 + num3 + num4)); }
Than, I want to say that you can not be able to implement the function overloading in JavaScript like this. Because of the every declaration of the add function, you are overwriting the previous one declaration. So when you call the function add than every time it will call the last declared function.
If you call the add function with different different arguments than every time last declared add function will called, here that is add function with 4 arguments.
add(1, 2); add(1, 2, 3); add(1, 2, 3, 4); //add with 4 arguments: NaN //add with 4 arguments: NaN //add with 4 arguments: 10
But if you want to create the simple function of the addition with any number of arguments, than it is better to use the arguments array, because the JavaScript is creating the arguments array for every function with the collection of the arguments.
function add() { var add = 0; for (var i = 0; i < arguments.length; i++) { add += arguments[i]; } document.writeln("Addition is: " + add); } add(1, 2); add(1, 2, 3); add(1, 2, 3, 4); //Addition is: 3 //Addition is: 6 //Addition is: 10
Function Overloading Workaround (Poly fill)
But if you want to really create the function overloading than you can follow the below methodology, It will definitely work for you.
function message(msg, fun) { if (arguments.length == 2) { if (typeof fun == "function") { fun(msg); } } else { document.writeln("DEFAULT FUNCTION: " + msg); } } message("Hello world!!!"); message("Hello world!!!", function (msg) { document.writeln("FUNCTION OVERLOADING: " + msg); }); //DEFAULT FUNCTION: Hello world!!! //FUNCTION OVERLOADING: Hello world!!!
Or you can also implement like this.
function message(msg, fun) { if (arguments.length == 2) { if (typeof fun == "function") { fun(msg); } } else { document.writeln("DEFAULT FUNCTION: " + msg); } } function overloadFunction(msg) { document.writeln("FUNCTION OVERLOADING: " + msg); } message("Hello world!!!"); message("Hello world!!!", overloadFunction); //DEFAULT FUNCTION: Hello world!!! //FUNCTION OVERLOADING: Hello world!!!
I hope you enjoyed this article, please comment down your reviews about this.
Happy Coding!!!
🙂