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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.