Reputation: 10830
Why is only one alert message shown in the below code in Javascript?
var a = 1;
function f() {
var a = 2;
function n() {
alert(a);
}
n();
}
f();
Shouldn't 2 alert messages appear?
Upvotes: 0
Views: 113
Reputation: 19112
No there shouldn't. You only run the function f()
once, and within that, you only run the function n()
once. That means you only run the alert
once too, so that's why there appears only one alert message.
It works like this basically:
a
f()
f()
a
n()
n()
a
As you can see, it only runs the part of the alert once, not twice
Upvotes: 3
Reputation: 1219
Only function 'n' calls alert(a). Even though function 'n' is inside function 'f', triggering function 'f' does not automatically trigger the embedded function n; only n() does that. Hence, the order of action for your code is:
Upvotes: 1
Reputation: 46309
You possibly have a misunderstanding in the way that functions work. The function is not called when it is declared; only when it is called. Thus this code:
function f() {
var a = 2;
function n() {
alert(a);
}
n();
}
Will do nothing, because f
is not invoked. It seems that you're quite comfortable with this concept, but perhaps what you're not so comfortable with is that it also applies, in exactly the same way, within the function:
var a = 2;
function n() {
alert(a);
}
// n() has not been invoked yet, only defined.
n(); // n() has now been invoked.
It may also be worth noting that your first a
variable is never used in this program; the second a
variable is entirely separate (outside of f
, a
is still 1, and within f
, a
is always 2). This is because of variable scope.
Upvotes: 1
Reputation: 48270
The code calls f
which then calls n
and the alert is shown. I can't think of a reason the alert should be shown twice.
Upvotes: 1