1

In Javascript, if I declare variables with var in javascript outside of a function

var foo = 1;
var bar = 2;

function someFunction() {
    ....
}

are those variables within the scope of the document or the window? Furthermore, why does this matter? I know that if one declares a variable without var, then the variable is global.

Is there a simple way for me to test whether a variable falls within the scope of the document or the window?

John Hoffman
  • 17,857
  • 20
  • 58
  • 81
  • 2
    Possible duplicate of [Javascript variable scope](http://stackoverflow.com/questions/500431/javascript-variable-scope) – Rodrigue May 19 '12 at 17:41
  • read it here. http://mark-story.com/posts/view/picking-up-javascript-closures-and-lexical-scoping – atilkan May 19 '12 at 18:09

4 Answers4

4

var limits the scope of a variable to the function it was defined in, so variables defined at the top level with var will effectively have global scope.

If you assign a value to a variable that hasn't been scoped with var then it becomes global regardless of where you define it.

There is a good article on javascript scopes here: What is the scope of variables in JavaScript?

Community
  • 1
  • 1
web_bod
  • 5,728
  • 1
  • 17
  • 25
  • 3
    There is no block scope in JavaScript. – Andreas May 19 '12 at 17:36
  • loop isn't scoping as well. i edited your post to semantically correct this. – Eliran Malka May 19 '12 at 17:44
  • @web_bod That is not correct. Variables in JavaScript are limited by the function where they are contained in. `function foo() {if (1 == 1) { var x = "xyz"; } console.log(x); }` will log `"xyz"` **relates to a deleted comment** – Andreas May 19 '12 at 17:47
2

When you declare a function in JavaScript, it creates a scope.

When you declare a variable, it must have a var. The var determines what scope it belongs and where it is visible. If it has no var, then it's an "assignment" to a variable and the browser assumes that a variable with that name exists in the outer scopes.

When an assignment happens, the browser searches outwards until it reaches the global scope. If the browser does not see the assigned variable in the global scope, it will declare it in the global scope (which is not good)

for example, take the following as a demo of scope visibility and not actual working functions:

//global variables
var w = 20
var x = 10

function  foo(){
    function bar(){

        //we assign x. since it's not declared with var
        //the browser looks for x in the outer scopes
        x = 0;

        function baz(){

            //we can still see and edit x here, turning it from 0 to 1
            x = 1;

            //redeclaring a variable makes it a local variable
            //it does not affect the variable of the same name outside
            //therefore within baz, w is 13 but outside, it's still 20
            var w = 13;

            //declaring y inside here, it does not exist in the outer scopes
            //therefore y only exists in baz
            var y = 2;

            //failing to use var makes the browser look for the variable outside
            //if there is none, the browser declares it as a global                
            z = 3;
        }
    }
}

//w = 20         - since the w inside was "redeclared" inside 
//x = 1          - changed since all x operations were assigments
//y = undefined  - never existed in the outside 
//z = 3          - was turned into a global
Joseph
  • 117,725
  • 30
  • 181
  • 234
1
var foo = 1;

window.foo === foo;

JavaScript is a functional language and therefore any variable declared inside the scope of a function is only available in that function.

JS will actually go through each functions scope and look for a variable declared.

function setGlobal() {
    bar = 1; // gets set as window.bar because setGlobal does not define it
}
setGlobal();

// logs true and 1
console.log(window.bar === bar, bar); ​

http://jsfiddle.net/kXjrF/

So...

function logGlobal() {
    var bar;
    console.log( foo, window.foo ) // undefined, undefined
    function setGlobal() {
        // window.foo is now set because logGlobal did not define foo
        foo = 1;  
        bar = 2; // logGlobal's bar not window.bar
        function makePrivate() {
           var foo = 3; // local foo
           console.log( foo ); // logs 3
        }
        makePrivate(); // logs 3
    }
    setGlobal();
    console.log( foo, window.foo ); // logs 1, 1

}
Trevor
  • 11,269
  • 2
  • 33
  • 40
  • I didn't downvote but I would guess that the -1 is from your first small attempt to answer the question. Just `var foo = 1; window.foo === foo;` isn't really that good at all... – Andreas May 19 '12 at 17:41
  • 1
    **[a](http://stackoverflow.com/questions/3962604/is-javascript-a-functional-programming-language) [functional](http://www.ajaxonomy.com/2009/javascript/javascript-as-a-functional-language) [language](http://www.crockford.com/javascript/javascript.html)**? – Eliran Malka May 19 '12 at 18:07
0

as JavaScript has only function scope, variables defined by the var keyword are scoped to the containing function.

you can easily check for global scoping by opening the JavaScript console in the browser (or directly in your code), and typing:

varRef && console.log(varRef)
Eliran Malka
  • 15,821
  • 6
  • 77
  • 100