Search code examples
javascriptscoping

understanding scoping in javascript - using the same temporary element in two different functions


I was working on a jQuery plugin where I did something like this:

 function MyPlugin() { ... }

 MyPlugin.prototype = {
     foo: function() { ... },
     bar: function() { ... },
     baz: function() { ... }
 }

Now the foo function ran a loop, which called the bar function:

 foo: function() {
     for (i in this.values) {
         var result = this.bar(this.values[i]);
     }
 },


 bar: function(value) {
     var res = '';
     for (i in value) {
         // do something
     }
     return res;
 }

Now please ignore what the functions are actually doing here, the focus is the loop itself. I've noticed that, since I'm using i inside bar - it changes the value of i for foo as well.

I've read about javascript scoping before, but still the example really confuses me. Why is i slipping between functions like that? How does it make any sense? I ended up just using a different variable, but I'm wondering what's the right way to avoid this sort of problem.

Thanks in advance!


Solution

  • The variable is not only slipping between the functions, it's everywhere. As you haven't declared the variable in the functions, you are using a global variable.

    Declare the variable in each function, and each function will have its own variable and leave the global scope alone:

    foo: function() {
      for (var i in this.values) {
         var result = this.bar(this.values[i]);
      }
    },
    
    
    bar: function(value) {
      var res = '';
      for (var i in value) {
         // do something
      }
      return res;
    }