728x90

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:

  1. Using different names in the first place
  2. Using optional arguments like y = y || 'default'
  3. Using number of arguments
  4. Checking types of arguments
  5. Or how?

javascriptoverloading

share  improve this question  follow 

edited Jul 2 '15 at 7:47

Sergey Maksimenko

5606 silver badges20 bronze badges

asked Jan 19 '09 at 0:06

hamdiakoguz

13.6k9 gold badges30 silver badges27 bronze badges

  • 16

    Perhaps it would be useful to ask why you think you need function overloading to begin with. I think that will get us closer to a real solution. – Breton Jan 19 '09 at 0:41

  • 1

    This is closed, but I do the following: this.selectBy = { instance: selectByInstance, // Function text: selectByText, // Function value: selectByValue // Function }; – Prisoner ZERO Jun 22 '12 at 20:46

  •  

    My answer shows how to do run time function overloading, it has a speed penalty and I wouldn't advise doing it to get around Javascript's specification. Function overloading is really a compile time task, I only provide the answer for academic purposes and leave it up to your own discretion as to whether or not to employ it in code. – Keldon Alleyne Oct 23 '12 at 22:57

  • 2

    Just in case it is useful, I've built a lightweight js framework that allows for type-based method overloading. Obviously the same caveats apply with regards to performance, but it's worked well for my needs so far and still has quite a lot of room for improvement: blog.pebbl.co.uk/2013/01/describejs.html#methodoverloading – Pebbl Jan 15 '13 at 0:24

add a comment

37 Answers

ActiveOldestVotes

1

2Next

626

 

The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.

What most developers do is tack on an object as the last argument to their methods. This object can hold anything.

 

 

function foo(a, b, opts) {
  // ...
  if (opts['test']) { } //if test param exists, do something.. 
}


foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});

 

 

 

179

I often do this:

C#:

public string CatStrings(string p1)                  {return p1;}
public string CatStrings(string p1, int p2)          {return p1+p2.ToString();}
public string CatStrings(string p1, int p2, bool p3) {return p1+p2.ToString()+p3.ToString();}

CatStrings("one");        // result = one
CatStrings("one",2);      // result = one2
CatStrings("one",2,true); // result = one2true

JavaScript Equivalent:

function CatStrings(p1, p2, p3)
{
  var s = p1;
  if(typeof p2 !== "undefined") {s += p2;}
  if(typeof p3 !== "undefined") {s += p3;}
  return s;
};

CatStrings("one");        // result = one
CatStrings("one",2);      // result = one2
CatStrings("one",2,true); // result = one2true

his particular example is actually more elegant in javascript than C#. Parameters which are not specified are 'undefined' in javascript, which evaluates to false in an if statement. However, the function definition does not convey the information that p2 and p3 are optional. If you need a lot of overloading, jQuery has decided to use an object as the parameter, for example, jQuery.ajax(options). I agree with them that this is the most powerful and clearly documentable approach to overloading, but I rarely need more than one or two quick optional parameters.

EDIT: changed IF test per Ian's suggestion

share  improve this answer  follow 

edited Jul 2 '15 at 17:11

 

answered Feb 15 '12 at 17:19

rocketsarefast

3,6941 gold badge18 silver badges18 bronze badges

  • 17

    Parameters which are not specified are undefined in JS, not null. As a best practice, you should never set anything to undefined, so it should not be a problem as long as you change your test to p2 === undefined. – Tamzin Blake Aug 31 '12 at 17:49

  • 3

    If you pass false as the last argument then it won't concatenate "false" to the end, because the if(p3) won't branch. – dreamlax Oct 23 '12 at 5:50

  • 6

    Just a quick note, your typeof p2 === "undefined" is probably the reverse of what you're expecting in the instance of your example, I think typeof p2 !== "undefined" is what you intended. Also, May I suggest being its supposed to concatenate string, number, and boolean that you actually do p2 === "number"; p3 === "boolean" – WillFM Apr 23 '13 at 2:56 

  • 8

    I like doing this: p3 = p3 || 'default value'; – Dorian Jun 17 '14 at 15:46 

  • 3

    What is the meaning of === and !==? Why not just use == and !=? – Ricardo Cruz Mar 2 '16 at 19:41 

show 7 more comments

+ Recent posts