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
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
Naming Convention
Another approach is to use a naming convention to differentiate variables with similar names in different scopes. This could involve prefixing or suffixing variable names to indicate their scope, making it easier to distinguish between them.
Syntax:
let outerVariable = 10;
function exampleFunction() {
let outerVariable = 20;
// ...
}
Example: To demonstrate the variable shadowing in JavaScript functions.
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
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
Contact Us