Course contentsShow
← JavaScript
Lesson 85 of 2,7233. Variables and ScopeFree lesson

Shadowing Variables

Inner scope variables with the same name hide outer scope variables of that name.

Shadowing Variables

You'll learn how a variable declared in an inner scope can "hide" an outer variable with the same name.

What is Shadowing?

When you declare a variable inside a nested scope (like a function or block) using the same name as a variable in an outer scope, the inner variable shadows the outer one. Within that inner scope, the name now refers to the inner variable only—the outer variable becomes temporarily invisible, as if hidden in a shadow.

How It Works

let color = "blue";

function paint() {
  let color = "red"; // This shadows the outer 'color'
  console.log(color); // "red" - refers to the inner variable
}

paint();
console.log(color); // "blue" - outer variable is unchanged

Inside the paint function, color refers to the inner "red" variable. The outer "blue" variable still exists in global scope, but the scope chain stops at the first match it finds—the inner one.

A Helpful Analogy

Imagine two people named "Alex" at a party—one in the main room (outer scope) and one in a smaller side room (inner scope). If you're standing in the side room and call out "Alex!", the person in that room responds. You can't see or reach the "Alex" in the main room from where you are, even though they still exist.

Why It Matters

Shadowing is common and usually intentional, but it can cause confusion if you forget an outer variable exists with the same name. You might think you're modifying the outer variable when you're actually only changing a local one.

Key Takeaway: When an inner scope declares a variable with the same name as an outer scope variable, the inner declaration shadows (hides) the outer one within that scope.