Trusted answers to developer questions

Lexical scope in JavaScript

Educative Answers Team

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.

svg viewer

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 10
var func = function (){ // outermost function
var b = 20;
console.log("a and b is accessible (outer):", a, b);
var innerFunc= function (){ // innermost function
var c = 30;
console.log("a and b and c is accessible (innner):", a, b, c);
func(); // invoke function func
console.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.


Copyright ©2023 Educative, Inc. All rights reserved
Trusted Answers to Developer Questions

Related Tags

Keep Exploring
Related Courses