Last Updated: February 25, 2016
· steveniseki

JavaScript function overloading

This is a simple example of function overloading in JavaScript using closures to overload a Users.find() method, we can overload the method with either a name or a first name, last name.

Thanks to Steve Jansen for this example

 function findAll() {
   // Find all users...

 function findByFullName(name) {
  // Find a user by name

  function findBySurname(first, last) {
     // Find a user by first and last name

  Users.prototype.find = function find() {
    if (arguments.length === 0)
       return findAll.apply(this);

    if (arguments.length === 1 and typeof(arguments[1]) === 'string')
      return findByFullName.apply(this, arguments);

   // by default, search using first and last name
   return findBySurname.apply(this, arguments);
Say Thanks

1 Response
Add your response

Szzueolm normal
over 1 year ago ·