Lexical scope is the ability for a function scope to access variables from the parent scope. We call the child function to be lexically bound by that of the parent function. The diagram below outlines the supposed hierarchy that the lexical scope maintains in JavaScript.
In the illustration above, we can see that, due to lexical scope, the functions may access all variables from their parent scopes up to the global scope, but no scope may access any variables from the functions defined inside it.
Take a look at the code below:
var a = 10; // variable a assigned to 10var func = function (){ // outermost functionvar b = 20;console.log("a and b is accessible (outer):", a, b);var innerFunc= function (){ // innermost functionvar c = 30;console.log("a and b and c is accessible (innner):", a, b, c);}innerFunc();return;}func(); // invoke function funcconsole.log("only a is accessible (global):", a);
In the above code, the value of variable a
is accessible by all function scopes since it is in the global scope. Meanwhile, variable b
is not accessible outside the function assigned to func
. This is because the variable is of local scope for the function assigned to variable func
. Another thing to note is that the function assigned to the innerFunc
variable can access variable b
and c
. This is because the inner functions are lexically bound by the outer functions.
Let's see another example that explains the concept of inner scope and outer scope:
function outer() {var x = 20;function inner() {var y = 30;console.log(y); // Accessible because of lexical scope}inner();// console.log(y); // This would result in an error as z is not accessible here}outer();
We declared a variable x
scope of function outer
, and another variable y
in the function inner
. The inner function has access to both its own scope (inner
) and the scope of its parent function (outer
), demonstrating lexical scoping. Variable y
is not accessible outside of the inner
function because it is limited to the lexical scope of that function.
NOTE: JavaScript uses a scope chain to find variables accessible in a certain scope. When a variable is referred to, JavaScript will look for it in the current scope and continue to parent scopes until it reaches the global scope. This chain of traversed scopes is called the scope chain.