JavaScript may not support Function Overloading, but we can simulate the behavior.
What is Function Overloading
function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. -- Function overloading
Other Languages
In other languages, an overloaded function can be created by adding another function with the same name.
// C#
void doThing(int x)
{
Console.WriteLine("int x");
}
void doThing(string y)
{
Console.WriteLine("string y");
}
This can't be done in JavaScript because the 2nd function will overwrite the 1st function.
Simulate the Behavior of Function Overloading
What I would like to do is to have a named argument function, but also support traditional arguments. So I would like to be able to call my function both of the following ways and have it work.
// Traditional
doThing(3, 4);
// Named Arguments
doThing({ x: 3, y: 4 });
One method of simulation this behavior is to detect the function argument types.
function doThing(x, y) {
// detect named argument object
if (typeof x === 'object' && x != null) {
return doThing(x.x, x.y)
}
console.log({ x, y })
}
// ✅ Now both styles work!
doThing(3, 4);
doThing({ x: 3, y: 4 });
In this example, the first argument x
is tested to see if it is of type object
. If it matches, the the function is called with the parameters pulled from x
.
Recommended Behavior
Because JavaScript doesn't natively support Function Overloading, it is usually recommended to create two separate functions and not attempt to overload functions.
// Sometimes it is better to create two separate functions.
function readFile(fileName) { /* code */ }
function readFileContents(contents) { /* code */ }
But because I just want to support named arguments as well as maintain backward compatibility with traditional arguments. So in this instance, I find the Simulated Function Overloading above an acceptable solution too.
tl;dr
JavaScript doesn't natively support Function Overloading, but we can simulate this by checking the parameter types. Prefer creating two separate functions for the different behaviors. But in some cases, Simulated Function Overloading is also a good solution.
- Check out my 📰 Newsletter
- Subscribe to my 📺 YouTube, JoelCodes
- Say hi to me on Twitter @joelnet
Cheers 🍻
Photo by israel palacio on Unsplash
Top comments (0)