0

Since there are two separate functions involved, namely _GetFoo and _CountBar shouldn't the variable bar be in a different scope even though they both use it? If you copy paste this and then run it, it will display the problem with two alerts.

<script type="text/javascript">
 var example = function () {

    var Foo = [];

    function _BuildFoo(size) {
        for (var buildSize = 0; buildSize < size; buildSize++) {
            Foo.push(buildSize);
        }
    }

    function _GetFoo(index) {
        for (bar in Foo) {
            //do Foo bar
        }
    }

    function _CountBar() {
        for (bar in Foo) {
         alert(bar); //bar = 0
         _GetFoo(1);
         alert(bar); //bar is incremented from _GetFoo function and is now 19
         break;
        }
    }

    return {
        _CountBar: _CountBar,
        _BuildFoo: _BuildFoo
    }
}

var foobar = new example();
foobar._BuildFoo(20);
foobar._CountBar();
</script>

Why do _GetFoo and _CountBar share scope?

1
  • 2
    Because without being bound to each function's scope, JS assumes that bar is attached to the global scope. Try var bar; for (bar in Foo) /* ... */ instead :^) Commented May 20, 2012 at 21:12

4 Answers 4

4

Without the keyword var, bar becomes a global variable. You need:

for (var bar in Foo) {

or alternatively,

var bar;
for (bar in Foo) {
Sign up to request clarification or add additional context in comments.

Comments

1

They both share example because they both are in a function.

Also, bar is not declared, and JavaScript will assume it is global.

Comments

0

No, bar is not declared as a local variable in the function scope.

But there's something worse: Never use for-in-loops for arrays!

var foo = [];
for (var i=0; i<foo.length; i++)
    // do something with foo[i]

Comments

0

Just to expand a little the other answers, there are two ways to avoid creating global vars through functions:

  • Use the var keyword, e.g var foo
  • Create the variable in the function parameters, e.g function myFunc(foo)

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.