0
var a = 1;

function b() {
    function a() {}; // local scope
    a = 10; // global scope
}
b();
alert(a);

It alerts 1 and not 10. I am wondering why is it so?

Salman Virk
  • 10,525
  • 8
  • 31
  • 44

3 Answers3

7

A function name and a variable are essentially the same thing in Javascript. You can declare a function via:

var a = function () {};

Which is the same as function a() {} for most intents and purposes. Both create a symbol in the current scope and make that symbol's value a function.

What you're doing is you're shadowing the global a with your own local a. It makes no difference whether this local a was defined via var a or function a.

deceze
  • 471,072
  • 76
  • 664
  • 811
3

Your code is the same as this:

var a = 1;

function b() {
    var a = function () {}; // local scope
    a = 10;
}
b();
alert(a);

Thus, the declaration of your local scope function creates a new local variable named a that initially has a function assigned to it, but you then reassign it to the value of 10. The higher scoped a is not touched by this inner assignment.

If the outer a definition is in the global scope, then you could assign to it with:

 window.a = 10;

If it is not in the global scope, then it has been "hidden" by the inner definition of a and there is no way to reach the outer a directly from the inner scope.

jfriend00
  • 580,699
  • 78
  • 809
  • 825
1

JavaScript is different from other languages:

JavaScript® (often shortened to JS) is a lightweight, interpreted, object-oriented language with first-class functions

What is first-class?

allows functions to be passed around just like any other value.

So as jfriend00 pointed out it converts the function into a variable locally in the function thus not changing the global variable.

Community
  • 1
  • 1
Robert Rocha
  • 8,656
  • 15
  • 59
  • 110