Lexical Environment in JavaScript:
A Lexical Environment in JavaScript is a place where JavaScript keeps track of the variables and functions available in a particular scope. It also keeps a reference to the outer scope, so JavaScript can find variables that are not available in the current scope.
In simple words, you can think of a lexical environment as a storage area for variables and functions along with a link to the outer scope.
When is a Lexical Environment created?
A lexical environment is created for a scope. For example, when a function is called, JavaScript creates a new lexical environment for that function. This environment contains its parameters and local variables.
Consider this example:
function outer() {
var x = 10;
function inner() {
console.log(x);
}
inner();
}
outer();
Here, outer() has its own lexical environment, which contains x.
The inner() function has its own lexical environment, but it can also access the lexical environment of outer() because inner() was written inside outer().
So, inner() can find x even though x is not declared inside inner().
How does JavaScript find a variable?
When JavaScript sees a variable name, it first looks in the current lexical environment.
If it doesn't find the variable there, it looks in the outer lexical environment.
It continues moving outward until it finds the variable or reaches the global scope.
For example:
var name = "John";
function greet() {
console.log(name);
}
greet();
When JavaScript tries to find name inside greet(), it first checks greet()'s environment.
name is not there, so JavaScript looks in the outer environment. It finds name in the global environment.
If JavaScript cannot find the variable anywhere, it throws a ReferenceError.
The lookup works roughly like this:
greet() environment
↓
outer environment
↓
global environment

Top comments (0)