1

I'm currently trying to understand Javascript's interesting take on global vs local scope.

My question is that why would the following returns undefined?

var a = 100;
function local() {
    if (false) {
        var a = 50;
    }
    alert(a);
}

Additionally, I ran this:

var a = 100;
function local() {
    alert(a);
}

The result was a resounding: 100.

Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?

gdoron
  • 147,333
  • 58
  • 291
  • 367
Zhia Chong
  • 346
  • 2
  • 12
  • A good practice is to put your `var` statements at the top of the function body. – Šime Vidas Sep 17 '13 at 18:46
  • See this: http://stackoverflow.com/questions/2788159/turn-javascript-local-variable-into-global-variable – neoeahit Sep 17 '13 at 18:47
  • possible duplicate of [Why does shadowed variable evaluate to undefined when defined in outside scope?](http://stackoverflow.com/questions/1528320/why-does-shadowed-variable-evaluate-to-undefined-when-defined-in-outside-scope) – Bergi Sep 17 '13 at 18:56

3 Answers3

4

Because of hoisting.

It means every variable declaration get's popped to the top of the function so the actual code that runs is:

var a = 100;
function local(){
    var a;
    if (false)
        a = 50;

    alert(a);
}

It has very little to do with global VS. local, you simply hid the outer a variable with the inner a variable.

Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?

No


Regarding the question in the comment "In the case that I want to revert to using a global variable in case the if condition fails (which I intentionally did), how can I do so? ":

You can use eval:

var a = 100;
function local() {
    if (false) {
        eval('var a = 50;');
    }
    alert(a);
}

Live DEMO

But you should not!

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 1
    So, to get the "global", `a`, the OP should just remove the `var` keyword inside the function :-) – gen_Eric Sep 17 '13 at 18:46
  • @RocketHazmat, but this way he's not creating a new variable which I believe he did try to to create. – gdoron Sep 17 '13 at 18:48
  • He was asking about accessing the "global" `a`. So, removing `var` altogether, would allow him to do that :) – gen_Eric Sep 17 '13 at 18:50
  • In the case that I want to revert to using a global variable in case the if condition fails (which I intentionally did), how can I do so? – Zhia Chong Sep 17 '13 at 18:55
  • That's great, got to test it out on JSFiddle and everything checks out. So the idea is hoisting, which basically pushes all your variable definitions to the top at the function level. Thanks! – Zhia Chong Sep 17 '13 at 19:15
  • @ZhiaChong, it's great but you should never use eval for variable declarations. just google _eval evil_. – gdoron Sep 17 '13 at 19:58
1

JavaScript has function scope, not block scope (as many other programming languages). That means regardless where the var statement occurs (in your case, an if-branch that is not even executed), it declares a variable a in the function's local scope. It shadows the global a variable, but since it has no value assigned it returns undefined.

Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?

You can access the variable as a property of the global object (window in browser environments):

var a = 100; // global
function loc() {
    var a = 50;
    alert(window.a); // 100
    alert(a); // 50
}
loc();

However, you will hardly use this. Global variables are to be avoided in general, and in case of name clashes you should simply rename your local variable (for readability and maintainability at least).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

I know that if a variable is in defined inside a function using var, then it will have Local Scope.

I also know that any function has easy access to Global variable.

When I tested following in Console of Browser, first output was undefined.

It means that function nwf() was unable to access Global variable nw1

This is due to reference error which highlights importance of Strict Mode

To avoid such scenario, never re-declare and/or initialize any variable with same name inside and outside any function, just unlike following:-

var nw1 = 1; // var creates global scope outside function  

function nwf() {
  alert(nw1);
  var nw1 = 2; // var creates LOCAL scope inside function
  alert(nw1);
};
nwf();
SUKUMAR S
  • 187
  • 2
  • 8