Sitemap

Shadowing In Javascript

2 min readMar 27, 2024

--

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 let and const within blocks (like if statements or loops) are only accessible within that block.

Shadowing with var, let, and const:

  • var: var has 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 with var are accessible before they are declared).
shadowing in var

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.

Press enter or click to view image in full size
Shadowing in let and const

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.

Press enter or click to view image in full size
Shadowing in Function

Tips:

  • Use shadowing cautiously, especially with var, as it can lead to confusion.
  • let and const provide 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!

--

--