Shadowing In Javascript
Shadowing occurs when a variable declared within a smaller scope (like a function or block) has the same name as a variable declared in a larger (outer) scope. The inner variable “shadows” the outer variable, meaning the code within the inner scope will refer to the inner variable even though the outer variable exists.
Understanding Scopes:
- Global Scope: Variables declared outside of any function are in the global scope and are accessible throughout your code.
- Function Scope: Variables declared within a function are only accessible within that function and any nested functions within it.
- Block Scope (let and const): Variables declared with
letandconstwithin blocks (likeifstatements or loops) are only accessible within that block.
Shadowing with var, let, and const:
var:varhas function-level scope, so shadowing can occur within functions and the global scope. However, it can lead to unexpected behavior due to hoisting (variables declared withvarare accessible before they are declared).
let and const: let and const have block-level scope, so shadowing is more predictable. They create a new binding for the variable within the block, effectively hiding the outer variable.
Shadowing in Functions:
Get Sushant kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
Shadowing is commonly used within functions to create temporary variables with the same name as outer variables. This can be useful for specific purposes within the function without affecting the outer variable.
Tips:
- Use shadowing cautiously, especially with
var, as it can lead to confusion. letandconstprovide clearer scoping and are generally preferred for variable declarations.- If you need to access an outer variable within a shadowed scope, you can use the outer variable name directly.
By understanding shadowing, you can write cleaner and more predictable JavaScript code!








