Explicit Referencing
In this approach, we can explicitly reference the outer variable within the nested scope by using this or the outer scope’s object name. This ensures clarity and prevents unintended shadowing.
Syntax:
let outerScope = {
outerVariable: 10
};
function exampleFunction() {
let outerVariable = 20
//....
}
Example: Understanding Variable Scope: Accessing Outer Variables in JavaScript Functions.
let outerScope = {
outerVariable: 10
};
function exampleFunction() {
let outerVariable = 20
console.log(outerVariable);
}
exampleFunction();
// Output: 10
console.log(outerScope.outerVariable);
Output
20 10
Shadowing Properties in JavaScript
Shadowing properties in JavaScript refer to the scenario where a variable declared within a nested scope has the same name as a variable in its outer scope. This can lead to confusion and unexpected behaviour, as the inner variable may “shadow” the outer one, effectively hiding it from the outer scope.
Table of Content
- Avoidance
- Naming Convention
- Explicit Referencing