Useful Platitudes

Notes on programming by Daniel Mendel

Another Javascript Scope Gotcha

Consider this simple constructor:

1
2
3
4
5
6
7
8
function Counter(){
  var a = b = 0;
  this.count = function(){
      a++;
      b++;
      return a + b;
  }
}

It creates an object with a count method which increments a couple of private variables and then returns their sum.

Let’s create one and run count a few times:

1
2
3
4
5
6
7
8
var counterA = new Counter();

counterA.count();
// 2
counterA.count();
// 4
counterA.count();
// 6

Great! It works just as expected. Let’s create another one:

1
2
3
4
5
6
7
8
var counterB = new Counter();

counterB.count();
// 5
counterB.count();
// 7
counterB.count();
// 9

What the heck? That’s not what we expected to happen – remember when we created those private variables?

1
var a = b = 0;

The var keyword only applies to the first variable in a mass assignment expression, so b is a global! Don’t mix mass assignment and var.

with Thomas Ballinger