Kuby Block

Blog about programming, tech, society and more.

Overload in JavaScript

poster

Overload is an interesting feature, with the same method name, we can use it in different cases. As a previous post, I have told about overloading vs overiding in OOP. But in JavaScript, overload does not exist.

Simple case:

function fn(x) {
  console.log("function with one parameter");
}

function fn(x, y) {
  console.log("function with two parameters");
}

Invoke it:

fn(1); // Output: function with two parameters
fn(1, 2); // Output: function with two parameters

In JavaScript, overload does not exist. In JavaScript Web, function is also a property of object window, top function. So when you create a function with the same name with a previous function, your previous property (previous declared function) will be replace with this newer function.

So in our case, function fn with two parameters will replace function fn with one parameter. That is the reason for the result in our example.

If we change the order of function fn:

function fn(x, y) {
  console.log("function with two parameters");
}

function fn(x) {
  console.log("function with one parameter");
}

And result will be:

fn(1); // Output: function with one parameter
fn(1, 2); // Output: function with one parameter

function in javascript is not the same with method in java. Method in java is only invoked when having enough parameter(s), each parameter have its type, so when call a method, java could determine which method will be called. That is the reason why overload exists in java.

function in javascript don’t care about what input. It will use the final function was defined, and all arguments you have input. Then it will map arguments were input with parameter(s) which this function needed, and execute it.

How about method of class in javascript?

Unfortunately, methods of class in javascript work the same with method in object window. So when you define 2 method with the same name, javascript will use the final method with that name to execute.

Conclusion

JavaScript is a freedom language, it has pros and cons. Although overload does not exist in javascript, but there is a lot of interesting features beside that. Learn and use it properly.


comments powered by Disqus