Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How this simple javascript script actually works (might be scoping)? [duplicate]

Tags:

javascript

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.

like image 784
funguy Avatar asked Apr 28 '14 14:04

funguy


1 Answers

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).

like image 113
Denys Séguret Avatar answered Oct 22 '22 04:10

Denys Séguret