Reputation: 607
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.
Upvotes: 1
Views: 71
Reputation: 950
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.
Upvotes: 5
Reputation: 1477
Second function will be called in both the cases, as the your redefining the function definition.
Also there is no function overloading in javascript, in the second case change function signature( i.e arguments it takes) will redefine the same A function (defined 1st).
Upvotes: 2
Reputation: 105439
When a parser enters the script, it searches for var
statements and function
declarations and then creates those variables on the current scope (in your case it's a global scope). This process of searching and creating is called hoisting. So in your case when parsing the first function declaration is found. So, something like that happens:
scope.A = function A(){} // first function
Then parser continues searching and finds another function declaration. And the same happens:
scope.A = function A(){} // second function
As you can see, scope.A
now references second function.
Upvotes: 1
Reputation: 1630
In both cases the second function will be called because it overwrites the global variable A
when declared.
It's similar to writing:
var a = 1;
var a = 2;
a === 2; // true
Upvotes: 0