Overloading vs Overriding in JavaScript

By | April 17, 2019

JavaScript does not support overloading.

JavaScript supports overriding, so if you define two functions with the same name, the last one defined will override the previously defined version and every time a call will be made to the function, the last defined one will get executed.

Example:

<script type="text/javascript">
function sum(x, y, z) {
return x + y + z;
}
function sum(x, y) {
return x + y;
}
var result = sum(1, 2, 3);
document.write(result);
</script>

Output: 3

In above example, the only function available is sum(x, y). So if we think we are making a call to sum(x, y, z), it’s actually calling sum(x, y). The remaining parameter(s) will be ignored.

We can also override Javascript built-in functions. The following example overrides the built-in JavaScript alert() function.

<script type="text/javascript"> 
 var alert = function(message) { 
 document.write(message); 
 } 
 // The following calls will invoke the overridden alert() function 
 alert("Learn "); 
 alert("JavaScript"); 
</script> 

I hope you will enjoy the Overloading and Overriding in JavaScript. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Like it? Share it