Site Navigation

Jan 5, 2009

Make Sure to Var Your Counters in JavaScript

While working on some JavaScript code today, I treated some for loops like I would in Java. Big mistake! If a variable in JavaScript is defined in a function without using the var keyword it has global scope. So let us just say, the second time you go through the for loop, hilarity ensues! lol.

This little problem would be a great way to teach about encapsulation and side effects. Moral of the story, always var your vars in JavaScript!

Post a Comment

Favorite Links Feed