10

Can anybody break down for me into steps how this (it looks simple in the first place) is interpreted by the browser:

var a = 1;
function b() {
    a = 10;
    function a() {}
}
b();
alert(a);

it will bring 1. If I would change a function name to anything else, etc:

var a = 1;
function b() {
    a = 10;
    function m() {}
}
b();
alert(a);

it will alert 10.

funguy
  • 2,072
  • 7
  • 30
  • 41
  • 1
    Arrgh, that example is so common that you even can put the full code in your favourite search engine and get helpful results… – Bergi Apr 28 '14 at 18:14

1 Answers1

13

The scope of a variable declared with var is the entire function in which it is declared, it doesn't start at the point of declaration. It's often described as variable declaration hoisting and can be seen as a move of all variable declarations to the start of the function. For function definitions, both the declaration and the "assignement" are moved together.

function b() {
    a = 10;
    function a() {}
}

is equivalent to

function b() {
    var a  = function() {};
    a = 10;
}

which means you declare a new variable a, and the a = 10 statement only changes the internal variable a, not the external one. We say the internal variable a shadows the external one.

In the second case, there's no variable a in the internal scope, which means the external one is used and changed (when looking for a variable, you go from the internal scope to the most external one following the closure chain).

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758