Learn to Code via Tutorials on Repl.it!

← Back to all posts
JS Function Overloading
h
MattDESTROYER

Many languages have the ability to overload functions. This means to have different variations of the same function depending on the input. JavaScript, however, does not support function overloading.
For example:

In this tutorial we will look at some simple ways of overloading functions in JavaScript!

The first way we will look at is very simple, we check if our input is defined or not. In JavaScript, parameters can be assigned a default value, but if you do not specify a default value, the parameter's default value is 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 object. arguments is an array-like 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 overloading in JavaScript. Now you can use the same function for many different types of input and numbers of parameters!

Voters
MuhammadSaefudi
VulcanWM
figglediggle
MattDESTROYER
Comments
hotnewtop
IMayBeMe

Not a JS user but very cool nonetheless.

MattDESTROYER
VulcanWM

Nice!

MattDESTROYER

@VulcanWM Thanks :D

VulcanWM