Classical (non-js) approach to overloading:
function myFunc(){
//code
}
function myFunc(overloaded){
//other code
}
Javascript wont let more than one function be defined with the same name. As such, things like this show up:
function myFunc(options){
if(options["overloaded"]){
//code
}
}
Is there a better workaround for function overloading in javascript other than passing an object with the overloads in it?
Passing in overloads can quickly cause a function to become too verbose because each possible overload would then need a conditional statement. Using functions to accomplish the //code inside of those conditional statements can cause tricky situations with scopes.
There are multiple aspects to argument overloading in Javascript:
Variable arguments – You can pass different sets of arguments (in both type and quantity) and the function will behave in a way that matches the arguments passed to it.
Default arguments – You can define a default value for an argument if it is not passed.
Named arguments – Argument order becomes irrelevant and you just name which arguments you want to pass to the function.
Below is a section on each of these categories of argument handling.
Variable Arguments
Because javascript has no type checking on arguments or required qty of arguments, you can just have one implementation of
myFunc()that can adapt to what arguments were passed to it by checking the type, presence or quantity of arguments.jQuery does this all the time. You can make some of the arguments optional or you can branch in your function depending upon what arguments are passed to it.
In implementing these types of overloads, you have several different techniques you can use:
undefined.arguments.length.argumentspseudo-array to access any given argument witharguments[i].Here are some examples:
Let’s look at jQuery’s
obj.data()method. It supports four different forms of usage:Each one triggers a different behavior and, without using this dynamic form of overloading, would require four separate functions.
Here’s how one can discern between all these options in English and then I’ll combine them all in code:
If the first argument passed to
.data()is a string and the second argument isundefined, then the caller must be using this form.If the second argument is not undefined, then set the value of a particular key.
If no arguments are passed, then return all keys/values in a returned object.
If the type of the first argument is a plain object, then set all keys/values from that object.
Here’s how you could combine all of those in one set of javascript logic:
The key to this technique is to make sure that all forms of arguments you want to accept are uniquely identifiable and there is never any confusion about which form the caller is using. This generally requires ordering the arguments appropriately and making sure that there is enough uniqueness in the type and position of the arguments that you can always tell which form is being used.
For example, if you have a function that takes three string arguments:
You can easily make the third argument optional and you can easily detect that condition, but you cannot make only the second argument optional because you can’t tell which of these the caller means to be passing because there is no way to identify if the second argument is meant to be the second argument or the second argument was omitted so what’s in the second argument’s spot is actually the third argument:
Since all three arguments are the same type, you can’t tell the difference between different arguments so you don’t know what the caller intended. With this calling style, only the third argument can be optional. If you wanted to omit the second argument, it would have to be passed as
null(or some other detectable value) instead and your code would detect that:Here’s a jQuery example of optional arguments. both arguments are optional and take on default values if not passed:
Here’s a jQuery example where the argument can be missing or any one of three different types which gives you four different overloads:
Named Arguments
Other languages (like Python) allow one to pass named arguments as a means of passing only some arguments and making the arguments independent of the order they are passed in. Javascript does not directly support the feature of named arguments. A design pattern that is commonly used in its place is to pass a map of properties/values. This can be done by passing an object with properties and values or in ES6 and above, you could actually pass a Map object itself.
Here’s a simple ES5 example:
jQuery’s
$.ajax()accepts a form of usage where you just pass it a single parameter which is a regular Javascript object with properties and values. Which properties you pass it determine which arguments/options are being passed to the ajax call. Some may be required, many are optional. Since they are properties on an object, there is no specific order. In fact, there are more than 30 different properties that can be passed on that object, only one (the url) is required.Here’s an example:
Inside of the
$.ajax()implementation, it can then just interrogate which properties were passed on the incoming object and use those as named arguments. This can be done either withfor (prop in obj)or by getting all the properties into an array withObject.keys(obj)and then iterating that array.This technique is used very commonly in Javascript when there are large numbers of arguments and/or many arguments are optional. Note: this puts an onus on the implementating function to make sure that a minimal valid set of arguments is present and to give the caller some debug feedback what is missing if insufficient arguments are passed (probably by throwing an exception with a helpful error message).
In an ES6 environment, it is possible to use destructuring to create default properties/values for the above passed object. This is discussed in more detail in this reference article.
Here’s one example from that article:
Then, you can call this like any of these:
The arguments you do not list in the function call will pick up their default values from the function declaration.
This creates default properties and values for the
start,endandstepproperties on an object passed to theselectEntries()function.Default values for function arguments
In ES6, Javascript adds built-in language support for default values for arguments.
For example:
Further description of the ways this can be used here on MDN.