Dev.to · 2 min read

Lexical Scope in JavaScript

Lexical Scope in JavaScript

Introduction In JavaScript, scope means the area where a variable can be accessed. There are different types of scope in JavaScript. One important concept is Lexical Scope. Lexical Scope means that the accessibility of a variable is decided by where the variable is declared in the code. In simple words: Where we declare a variable decides where we can use it. Example of Lexical Scope Let's see a simple example: let name = "Abishek"; function greet() { console.log(name); } greet(); The output will be: Abishek Here, name is declared outside the greet() function. Since greet() is inside the outer scope, it can access the name variable. This shows that an inner scope can access variables from its outer scope. Inner and Outer Scope Consider another example: function outer() { let message = "Hello"; function inner() { console.log(message); } inner(); } outer(); Here, message is declared inside the outer() function. The inner() function is inside outer(), so it can access message. But the opposite is not possible. A variable declared inside a function cannot normally be accessed from outside that function. So we can remember: Inner Scope → Outer Scope ✅ Outer Scope → Inner Scope ❌ Lexical Scope and Scope Chain Lexical Scope is also connected to the Scope Chain. When JavaScript needs a variable, it first checks the current scope. If it cannot find the variable, it checks the outer scope and continues searching until it finds the variable. For example, an inner function can access its own variables and variables from its outer functions. Conclusion Lexical Scope is a simple but important concept in JavaScript. It tells us that the location where a variable is declared determines where it can be accessed.

This is a summary aggregated from Dev.to. Read the complete article on the original site:

Read full article at Dev.to

More Programming & Dev News