Javascript Trivia

I guess I should have learned this a long time ago - but when a tiny piece of code kicks my ass this bad, I like to share it with the world :) How many times do you expect the following Javascript to alert 'hi'?

function x() {
  for(i=0; i<8; i++) {
function y() {
  for(i=0; i<2; i++) {

The answer - An infinite number of times! Believe it or not, when the Javascript interpreter comes across a variable without the var keyword in front of it, it automatically creates a global variable with the given variable name. Fun stuff.

blog comments powered by Disqus