Skip to content
Advertisement

What is lexical scope?

What is a brief introduction to lexical scoping?

Advertisement

Answer

I understand them through examples. ๐Ÿ™‚

First, lexical scope (also called static scope), in C-like syntax:

JavaScript

Every inner level can access its outer levels.

There is another way, called dynamic scope used by the first implementation of Lisp, again in a C-like syntax:

JavaScript

Here fun can either access x in dummy1 or dummy2, or any x in any function that call fun with x declared in it.

JavaScript

will print 5,

JavaScript

will print 10.

The first one is called static because it can be deduced at compile-time, and the second is called dynamic because the outer scope is dynamic and depends on the chain call of the functions.

I find static scoping easier for the eye. Most languages went this way eventually, even Lisp (can do both, right?). Dynamic scoping is like passing references of all variables to the called function.

As an example of why the compiler can not deduce the outer dynamic scope of a function, consider our last example. If we write something like this:

JavaScript

The call chain depends on a run time condition. If it is true, then the call chain looks like:

JavaScript

If the condition is false:

JavaScript

The outer scope of fun in both cases is the caller plus the caller of the caller and so on.

Just to mention that the C language does not allow nested functions nor dynamic scoping.

Advertisement