0
0
JavascriptConceptBeginner · 3 min read

Variable Shadowing in JavaScript: What It Is and How It Works

Variable shadowing in JavaScript happens when a variable declared inside a certain scope (like a function or block) has the same name as a variable declared in an outer scope. The inner variable "shadows" or hides the outer one within its scope, so references to that name use the inner variable instead.
⚙️

How It Works

Imagine you have a box inside a bigger box. If both boxes have a label with the same name, when you look inside the smaller box, you only see the label inside it, not the one in the bigger box. Variable shadowing works the same way in JavaScript.

When you declare a variable inside a function or block with the same name as one outside, the inner one hides the outer one while you are inside that inner scope. This means any code inside the inner scope uses the inner variable, not the outer one.

This helps keep variables organized and prevents accidental changes to variables outside the current scope, but it can also cause confusion if you forget about the shadowing.

💻

Example

This example shows a variable name declared outside and inside a function. Inside the function, the inner name shadows the outer one.

javascript
const name = 'Alice';

function greet() {
  const name = 'Bob'; // This shadows the outer 'name'
  console.log('Hello, ' + name);
}

greet();
console.log('Outside function: ' + name);
Output
Hello, Bob Outside function: Alice
🎯

When to Use

Variable shadowing is useful when you want to use the same variable name in different parts of your code without mixing their values. For example, inside a function, you might want a temporary variable with the same name as a global variable but with a different value.

This helps keep your code clean and avoids accidental changes to important variables outside the current scope. However, use it carefully to avoid confusion, especially in large codebases.

Key Points

  • Variable shadowing happens when an inner scope variable has the same name as an outer scope variable.
  • The inner variable hides the outer one within its scope.
  • It helps keep variables local and prevents accidental changes to outer variables.
  • Be careful to avoid confusion by using clear variable names or comments.

Key Takeaways

Variable shadowing occurs when a variable in an inner scope uses the same name as one in an outer scope, hiding the outer variable.
Inside the inner scope, references to the variable name use the inner variable, not the outer one.
Shadowing helps keep variables local and prevents unintended changes to outer variables.
Use shadowing carefully to avoid confusion and bugs in your code.