Thursday, February 02, 2006

JavaScript Variable Scoping

Although JavaScript has variable scoping it only has two scopes, global and function. Being a Java programmer this caught me out as I had some JavaScript in a function:
  var i = 8;
  if ( i ) {
     var i = 2;
  }
  alert(i);
Which I thought should tell me i was 8 at the end as the second i should only be available in the if statement but actually the i declared inside the if is the same variable as the one declared on the first line.