In the world of JavaScript, understanding lexical scope and closures is crucial for writing efficient and maintainable code. These concepts may seem daunting at first, but once you grasp them, they become powerful tools in your arsenal. In this article, we’ll dive into lexical scope and closures, exploring them through practical examples and code snippets.
Lexical Scope: Where Variables Live
Lexical scope, also known as static scope, refers to the accessibility of variables based on their physical location within the source code. In simpler terms, it determines where a variable is available for use. JavaScript uses lexical scoping, which means the scope of a variable is determined at compile time, not at runtime.
Let’s start with a basic example:
function outerFunction() {
const outerVar = 'I am outside the innerFunction';
function innerFunction() {
console.log(outerVar); // Output: 'I am outside the innerFunction'
}
innerFunction();
}
outerFunction();
In this example, the variable outerVar
is declared within the outerFunction
. However, it's accessible…