function overloading in JavaScript

What is function overloading in JavaScript?

There is no real function overloading in JavaScript and it allows to pass any number of parameters of any type.

You have to check inside the function how many arguments have been passed and what is the type arguments using typeof.
The example for function overloadingnot supporting in JavaScript as give below.

function sum(a, b) {
    alert(a + b);
}

function sum(c) {
    alert(c);
}

sum(3);//The output is 3.
sum(2, 4);//The output is 2.

In the JavaScript, when we write more than one functions with same name that time JavaScript consider the last define function and override the previous functions. You can see the above example output for the same.

We can achieve using the several different techniques as give below

  1. You can check the declared argument name value is undefined.
  2. We can check the total arguments with arguments.length.
  3. Checking the type of passing arguments.
  4. Using number of arguments
  5. Using optional arguments like x=x || 'default'
  6. Using different name in the first place
  7. We can use the arguments array to access any given argument by using arguments[i]

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^