Open In App

Shadowing Properties in JavaScript

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

JavaScript
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.

JavaScript
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.

JavaScript
let outerScope = {
    outerVariable: 10
};

function exampleFunction() {
    let outerVariable = 20
    console.log(outerVariable);
}

exampleFunction();
// Output: 10
console.log(outerScope.outerVariable);

Output
20
10

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads