Scoping rules

R. Alexander Miłowski

milowski@ischool.berkeley.edu

School of Information, UC Berkeley

What is scope?

It's complicated:

Global Scope

var x = 10;
function test() {
   alert(x);
}
         

The result is 10.

A the top level, every variable is accessible unless somehow obscured by something local.

Local Scope

var x = 10;
function apple(x) { 
   alert(x); 
}
function orange() { 
   var x = 30; alert(x);
}
apple(20); orange();

The result is 20, 30.

The local scope obscures the global scope.

Beware of this:

function orange() {
   x = 30
}

Block Scope?

Yeah, no. You lose.

var x = 10;
function blockTest() {
   if (true) {
       var x = 20;
   }
   alert(x);
}

Is the same as:

var x = 10;
function blockTest() {
   var x;
   if (true) {
       x = 20;
   }
   alert(x);
}

What does this do? for (var i=0; i<10; i++) {}; alert(i);

The this variable