JS Function Overloading
Many languages have the ability to overload
functions. This means to have different variations of the same
In this tutorial we will look at some simple ways of overloading
undefined. We can check if a parameter is
undefined or not to see if a value has been input.
Without that simple overload you would see
Foo1 - fiz: foo, baz: undefined if only
'foo' was input.
Another way we can overload a
function based on the number of paramters input is to use the
arguments is an
object that stores information on the values input in a
function. We can use the
length property of
arguments to check how many parameters had an actual value input.
One of the most useful abilities of
function overloading is the ability to take in different types of input and evaluate them different based on their type. We can use the
instanceof operator to check if an
object is an instance of a specific class and we can use the
typeof operator to check the type of a variable. (eg:
variable instanceof Class,
typeof variable === "type")
That last function overloading trick is probably the most useful, in the above example it allows you to use a number of different combinations of types to perform to do the same thing. Without
function overloading you would be force to write multiple different functions for specific types or convert types which can be messy and tedious.
By now you know a number of tricks you can use to recreate
function for many different types of input and numbers of parameters!