Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
lexical
scope

Lexical scope in JavaScript

Educative Answers Team

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πŸ’ͺ

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.

Code

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);
}
innerFunc();
return;
}
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.

RELATED TAGS

javascript
lexical
scope
Copyright Β©2022 Educative, Inc. All rights reserved

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πŸ’ͺ

Keep Exploring
Related Courses