I tried to write a function on a JS file and another function with the same name in the page.
I expected an error but no error came and I got only the function from the JS file to execute.
How is this possible? Even if I write a function in a separate JS file, everything is rendered in a single html file. Then how come it is possible?
<script type="text/javascript" language="javascript" src="JScript.js"></script>
<script language="javascript">
function Boo() {
alert("Hai new");
}
</script>
<button onclick="Boo();">Click</button>
and in the JS file
function Boo() {
alert("Hai");
}
JavaScript supports overriding not overloading, meaning, that 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.
Yes, variables belonging to different function can have same name because their scope is limited to the block in which they are defined. Variables belonging to different functions in a single code can have same name if we declare that variable globally as shown in the following code snippet below .
Function overloading is the ability to have multiple functions with the same name but with different signatures/implementations. When an overloaded function fn is called, the runtime first evaluates the arguments/parameters passed to the function call and judging by this invokes the corresponding implementation.
There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.
One aspect that not many people ever think about with JavaScript is that if you define multiple functions with the same name then the last one defined will be the one that actually runs. JavaScript functions are not polymorphic the way that functions in many other languages are in that JavaScript doesn't care if the actual arguments defined for the functions are different as it can't distinguish between them on that basis. Where in other languages you might have myfunc(oneparm) and myfunc(parmone, parmtwo) as two separate functions with the one that gets run depending on the number of parameters passed, in JavaScript the last one defined will always be the one run regardless of the number of parameters.
http://javascript.about.com/library/blpolyfunc.htm
Named functions in javascript are more like variables. If you change the value of a variable, no error occurs, the variable simply has a new value. The same can be said of a function in javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With