Variable Shadowing in JavaScript: What It Is and How It Works
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.
const name = 'Alice'; function greet() { const name = 'Bob'; // This shadows the outer 'name' console.log('Hello, ' + name); } greet(); console.log('Outside function: ' + name);
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.