What is Lexical Scope? Lexical scope is the rule that determines where a variable can be accessed based on where the code is written. The word lexical basically means that JavaScript determines the scope by looking at the structure of the code. It does not matter where a function is called from; what matters is where that function was defined. For example: let name = "John"; function greet() { console.log(name); } greet(); Here, name is declared outside the greet() function. Since greet() is written in the global scope, it can access name from that outer scope. This relationship is decided by the way the code is written. This is what we mean by lexical scope. Nested Scopes Scopes can exist inside other scopes. This is called nested scope. For example: function outer() { let name = "John"; function inner() { console.log(name); } inner(); } outer(); Here, inner() is written inside outer(). Because of this, inner() can access variables that belong to outer(). We can visualize the scopes like this: Global Scope │ └── outer() Scope │ └── inner() Scope The inner scope can access variables from its outer scope, but the outer scope cannot access variables that exist only inside the inner scope. For example: function outer() { function inner() { let age = 25; } console.log(age); // ReferenceError } age belongs to inner()'s scope. Therefore, outer() cannot directly access it. This idea also applies to blocks. A block created with { } can have its own scope when using let and const. This is called block scope, and it is also part of JavaScript's lexical scoping system. Lexical Scope and Lexical Environment Lexical scope and lexical environment are closely related, but they are not the same thing. Lexical scope describes the rules of accessibility. It tells us which variables a particular piece of code is allowed to access based on where that code is written. A lexical environment, on the other hand, is the internal structure JavaScript uses to keep track of variables and functions in a scope and their relationship with outer environments. So, a simple way to remember the difference is: Lexical scope is about where variables can be accessed, while a lexical environment is the internal structure that keeps track of those variables and their connection to outer scopes. Understanding lexical scope is important because it forms the foundation for understanding closures, where a function can continue to access variables from its surrounding scope even after the outer function has finished executing.