It has been said that there are two types of developer, the Wizard and the Scribe. Myself, I think I fall somewhere in between. The Scribe in me needs to know the definitions of words used, and also the context. Sometimes, especially when the pressure is on, I just do something that works without knowing the finer details, explaining things in a hand-wavy fashion. Not ideal. This is why, time permitting, I like to go back over code and dissect things, learning the finer points. Knowing the exact meaning of "Lexical Scope" is one of those things. Knowing the finer details helps when communicating about your code your code.

Lexical Scope

The definition given in Wikipedia is "the portion of source code in which a binding of a name with an entity applies." Let's split this into individual words.


Let's start off with the definition of "Lexical". I remember at Uni, one time our lecturer asked us "what is a Lexicon?" I was the only one who knew the meaning. It is simply a dictionary, or a vocabulary of something. The actual derivation is "book of words". So what? Well, why is "lexical" used with scope? JavaScript (I'm not including ECMAScript 6 which has block level scoping here) uses functional scope, not block level scope like some other languages. Any of the variables defined within the function body can be accessed from anywhere within that function. This means that a "dictionary" or "lexicon" of the variables are created for the scope of the given function. We can further define a closure as a functional object that has reference to the lexical scope it was created in.


The definition of scope in this context comes from "the extent, or area, or subject matter that is being dealt with or relevant." A more programming related definition of scope is on Wikipedia. So here we are, a Lexical Scope refers to the function's list of variables declared within it.