Lexical Scope

Scope defined statically, based on where definition of, say a variable, is within the source code. For example:


var x = 0;

function f() { return x; }

function g() { var x = 1; return f(); }

window.onload = function () {
var message = document.getElementById('LabelMessage');
message.innerHTML = g();
}

What we see displayed on the web page for “message” is: 0 (zero).

Why:

At the moment f() is defined, the value of “x” in the lexical scope (where it appears in the source code) is the value of “x” defined in line 1.

The scope of “var x = 1;” in function g() is g(). It is not in the same lexical scope of “var x = 0;” from line 1. Therefore, at the time f() is defined the only “var x” in scope is the one defined earlier on line 1.

To test this, we remove the “var” from in front of “x” in g(). Now what “x” in g() is referring to is the “x” on line 1. When we refresh the page, we see “1” displayed.

Another Observation:

In JsLint (www.jslint.com) the option to have one “var” block per function makes perfect sense.

Imagine if there were “var” declarations all over the code and in multiple places in a single function. Try figuring the which of the declared scopes is the right one!

No comments yet

Leave a comment