In most of the OOP languages like C#, we have a concept of function overloading, and we can achieve it with the same function name with different signatures and arguments.
But we don't have function signature in JavaScript. Let us take a look at what happens when we define two functions with the same name and different parameters.
- <script>
- function Num(number){
- document.write('You have passed '+number+"<br/>");
- }
- function Num(){
- document.write("You haven't passed any arguments<br/>");
- }
- Num();
- Num(1);
- </script>
Output
You haven't passed any arguments
In JavaScript, when you define multiple functions with the same name, the one that appears last will replace the earlier function declarations. This is called "function hosting". Now, let us take a look at using function objects,
- <script>
- var Num = new Function("number","document.write(\"You have passed <br/>\"+number)");
- Num = new Function("document.write(\"You haven't passed any arguments<br/>\")");
- Num();
- Num(1);
- </script>
Output
You haven't passed any argument
As you can see, the function object is being assigned to Num two times, so the first function object will be replaced.
We can achieve the overloading concepts with arguments object. This is different than other object oriented programming languages. We have defined only one function with no parameters but we are calling it with no parameters and more than one parameters.
- <script>
- function sum() {
- var msg = 0;
-
-
-
-
- if (arguments.length == 0) {
- msg = "You haven't passed any parameters<br/>";
- document.write(msg);
- }
-
- else if (arguments.length == 1) {
- msg = "Please pass atleast two parameters<br/>";
- document.write(msg);
- } else {
- var result = 0;
- var len = arguments.length;
-
- for (i = 0; i < len; i++) {
- result = result + arguments[i];
- }
- document.write(result + "<br/>");
- }
- }
- sum();
- sum(1);
- sum(1, 8);
- sum(1, 2, 5, 6, 67, 8, 8);
Output
You haven't passed any parameters
Please pass at least two parameters
9
97