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
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
Contact Us