ckv
ckv

Reputation: 10830

Why is only one alert message shown in the below code in Javascript?

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

Answers (4)

Joeytje50
Joeytje50

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:

  1. (line 1) Assign variable a
  2. (line 2-8) Create function f()
  3. (line 9) Run function f()
    1. (line 3) Assign variable a
    2. (line 4-6) Create function n()
    3. (line 7) Run function n()
      • (line 5) Alert the value of variable a
  4. end

As you can see, it only runs the part of the alert once, not twice

Upvotes: 3

Frankenscarf
Frankenscarf

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:

  1. Set 'a' equal to 1
  2. trigger f()
  3. set 'a' equal to 2
  4. trigger n()
  5. alert 'a'

Upvotes: 1

Dave
Dave

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

Wiktor Zychla
Wiktor Zychla

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

Related Questions