Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript scope gets changed? Why does this happen?

The value of 'a' seems to lose global scope when the constructor a is called.

var a = 6;

function b() {
    a = 10;

    function a() {}
    console.log(a); //10
}
b();
console.log(a); //6
like image 311
user2430508 Avatar asked May 28 '13 23:05

user2430508


2 Answers

The order is interpreted as shown below due to variable hoisting. Note that as @ShadowCreeper correctly points out, function a(){} is actually creating a local variable a inside of function b which is hoisted as shown below.

var a;
var b;

a = 6;
b = function() {
 var a;
 a = function(){};
 a = 10;
 console.log(a); //10
}
b();
console.log(a); //6
like image 181
Travis J Avatar answered Nov 14 '22 23:11

Travis J


Because you are creating a local variable (the function a) then replacing that local variable's value (the function) with 10.

One way to avoid things like this is to precede all local variables and functions with "_" (underscore).

like image 37
Shadow Man Avatar answered Nov 14 '22 23:11

Shadow Man