- Lexical scope is a way of determining variable scope based on where the variable is defined in the code. In JavaScript, the lexical scope is determined by the location of the function in which the variable is declared.
function outerFunction() {
const outerVariable = 'I am outside!';
function innerFunction() {
const innerVariable = 'I am inside!';
console.log(outerVariable); // Output: I am outside!
console.log(innerVariable); // Output: I am inside!
}
innerFunction();
}
outerFunction();
- In this example, we have an outerFunction that defines a variable called outerVariable. Within outerFunction, there is an inner function called innerFunction that defines a variable called innerVariable.
- When we call innerFunction from within outerFunction, it has access to both outerVariable and innerVariable because they are both in the scope of innerFunction. However, if we try to access innerVariable from outside of innerFunction, we'll get a reference error because it's out of scope.
- The concept of lexical scope is important to understand because it affects how variables are accessed and manipulated in JavaScript. Variables declared in an outer scope can be accessed by functions defined within that scope, but variables declared in an inner scope cannot be accessed by functions defined outside of that scope.
function outerFunction() {
const outerVariable = 'I am outside!';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const innerFunc = outerFunction();
innerFunc(); // Output: I am outside!
- In this example, we have an outerFunction that defines a variable called outerVariable. Within outerFunction, there is an inner function called innerFunction that logs the value of outerVariable to the console.
- When we call outerFunction, it returns innerFunction, which we assign to the variable innerFunc. When we call innerFunc, it logs "I am outside!" to the console.
- This is possible because innerFunction has access to outerVariable through lexical scope. outerVariable is in the scope of outerFunction, and since innerFunction is defined within outerFunction, it has access to outerVariable through closure.
- In summary, lexical scope in JavaScript refers to how variables are accessed based on their location in the code. Variables declared in an outer scope can be accessed by functions defined within that scope, but variables declared in an inner scope cannot be accessed by functions defined outside of that scope.
No comments:
Post a Comment