Course contentsShow
← JavaScript
Lesson 494 of 2,72313. ClosuresFree lesson

Scope Visibility Rules

Inner scopes can see outer variables, but outer scopes cannot see inner variables—the one-way visibility rule.

Scope Visibility Rules

You'll learn: How inner scopes can "see" outer variables, but outer scopes cannot see inner variables—JavaScript's one-way visibility rule.

The One-Way Mirror

Think of nested scopes like a one-way mirror in a police interrogation room. Code inside an inner scope (the interrogation room) can see everything in the outer scope (the observation room), but code in the outer scope cannot see what's happening inside the inner scope.

This is JavaScript's visibility rule: inner scopes have access to variables declared in outer scopes, but the reverse is never true.

How It Works

let outer = "I'm outside";

function showVisibility() {
  let inner = "I'm inside";
  
  console.log(outer); // ✓ Can see outer: "I'm outside"
  console.log(inner); // ✓ Can see inner: "I'm inside"
}

showVisibility();
console.log(outer); // ✓ Can see outer: "I'm outside"
console.log(inner); // ✗ ReferenceError: inner is not defined

The function showVisibility creates an inner scope. Inside that function, you can access both inner (defined locally) and outer (defined in the parent scope). But outside the function, inner doesn't exist—it's hidden from view.

Deeper Nesting

This rule applies at every level:

let level1 = "first";

function outer() {
  let level2 = "second";
  
  function inner() {
    let level3 = "third";
    console.log(level1, level2, level3); // ✓ All visible here
  }
  
  inner();
  console.log(level1, level2); // ✓ These work
  console.log(level3); // ✗ Error: can't see level3
}

Key Takeaway: Inner scopes can always look "outward" to parent scopes, but outer scopes can never look "inward" to child scopes—it's a one-way street that protects encapsulation.