What is the best way(s) to fake function overloading in Javascript?
I know it is not possible to overload functions in Javascript as in other languages.
If I needed a function with two uses foo(x)
and foo(x,y,z)
which is the best / preferred way:
- Using different names in the first place
- Using optional arguments like
y = y || 'default'
- Using number of arguments
- Checking types of arguments
- Or how?
I'm not sure about best practice, but here is how I do it:
We made over.js to solve this problem is a very elegant way. You can do:
I like @AntouanK's approach. I often find myself offering a function with different numbers o parameters and different types. Sometimes they don't follow a order. I use to map looking the types of parameters:
Since JavaScript doesn't have function overload options object can be used instead. If there are one or two required arguments, it's better to keep them separate from the options object. Here is an example on how to use options object and populated values to default value in case if value was not passed in options object.
here is an example on how to use options object
For your use case, this is how I would tackle it with
ES6
(since it's already the end of 2017):You can obviously adapt this to work with any amount of parameters and just change your conditional statements accordingly.
I've been using this function to prettify my overloads for years:
Demostrated:
Take a look at jQuery's
off
method:Many overloaded functions when optimized for performance are nigh unreadable. You have to decipher the head of the function. This is perhaps faster than using an
overload
function like I provide; however, it is slower from a human perspective with regard to identifying which overload was called.