Block scope in JavaScript

TorgoX on 2005-03-07T09:44:07

Dear Log,

JavaScript has scoped variables -- but no block-scope. So:

var x = 123;

function zot () {
  var x = 456;

  {
    var x = 789;
  }

  alert("oboy " + x.toString());
  return;
}

zot();

// pops up "oboy 789"

But there's function scope, so you can fake block-scope by making and then calling an anonymous function:

var x = 123;

function zot () {
  var x = 456;

  (function () {
    var x = 789;
  })();

  alert("oboy " + x.toString());
  return;
}

zot();

// pops up 456.