Avoidance
This approach involves avoiding the use of the same variable name in nested scopes to prevent shadowing. It’s a straightforward method but might not always be feasible, especially in complex code bases.
Syntax:
let outerVariable = 10;
function exampleFunction() {
// This shadows the outerVariable
let outerVariable = 20;
// ....
}
Example: Understanding Variable Scope in JavaScript: Shadowing Outer Variables.
let outerVariable = 10;
function exampleFunction() {
// This shadows the outerVariable
let outerVariable = 20;
// Output: 20
console.log(outerVariable);
}
// Output: 10
exampleFunction();
console.log(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