Introduction
It is true that JavaScript supports overriding, not overloading. When you define multiple functions that have the same name, the last one defined will override all the previously defined ones and every time when you invoke a function, the last defined one will get executed. The following example overrides the user-defined function.
JavaScript Demo - Overriding user-defined function
- <script type="text/javascript">
- function multiplyNum(x, y, z) {
- return x * y * z;
- }
- function multiplyNum(x, y) {
- return x * y;
- }
- var result = multiplyNum(1, 2, 3);
- document.write(result);
Output
2
Looking at the above example, the value of multiplication will be equal to 2 instead of 6.
We can also override Javascript's built-in functions. The following example overrides the built-in JavaScript alert() function.
JavaScript Demo - Overriding built-in 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>
Output
Learn JavaScript
By default, alert() function displays the message in the alert box. But here we have overridden it. Now it is displaying the message in the document.
I hope you enjoyed this article.
Thanks and regards.
Tej KumarPosted Oct 25, 2018, 5:14 AM
You are not passing the same number of parameters.....It is overloaded not override
Dean AlcornPosted Jul 27, 2018, 2:30 AM
Is it overloading or overriding?