Grokking the Behavioral Interview
Get Educative’s popular interview prep course for free.
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.
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.
RELATED TAGS