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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book