1

I am kind of novice in JavaScript, I really don't quite understand why the below code return 1 instead of 10:

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

The running code: http://jsfiddle.net/smMtU/

If I rem the line function a() {}, it returns 10 as expected. This code got from this post to explain the concept scoping and hoisting in JavaScript. Maybe I am missing something while reading this post?

Please anyone could point out the concept behind this code?

cweiske
  • 30,033
  • 14
  • 133
  • 194
cuongle
  • 74,024
  • 28
  • 151
  • 206

2 Answers2

7

Due to hoisting, your code is equivalent to

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

Inside b you're not changing the external a but an internal one.

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

This declaration creates a scope for the function a in the current scope before the execution.

When the function b is called and this line below is executed

a = 10;

there's already a scope a created inside the function b

So this becomes equivalent:

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

to this:

var a = 1;
function b() {
    var a = function(){}; //scope created before

    a = 10; //'a' already exists in local scope, just replace it.
    return;
}
b();
alert(a); // global 'a' remains intact
Vitim.us
  • 20,746
  • 15
  • 92
  • 109