I have confusion on function calling in javascript,Can some one tell answer for below question ?
**Question 1:**
function A(){
}
function A(){
}
A();
In this case,which function will call?is it first or second function? and why?
**Question 2:**
function A(a){
}
function A(a,b){
}
A();
In this case,which function will call?is it first or second function? and why?
Thanks in advance.
Let's put it in action and see the results:
function A(){
var el = document.getElementById('test');
el.innerText = "First function";
}
function A(){
var el = document.getElementById('test');
el.innerText = "Second function";
}
A();
<div id="test"></div>
As we can see, the second function is the winner. Why? Because when we write it again after a first declaration we just overwrite it really.
As for the second question:
function A(a){
var el = document.getElementById('test');
el.innerText = "First function";
}
function A(a,b){
var el = document.getElementById('test');
el.innerText = "Second function";
}
A();
<div id="test"></div>
As we see, it still executes the second question. That's because javascript isn't a polymorphic language, that is, it cannot have two function with the same name but with different input declarations like java does. We just did the same thing we did above: We overwrite the function A.
PS: If javascript were a polymorphic language (which it isn't), then the second run would return an error because we haven't declared an version of function A that receive 0 variables as input.