Function Scope Creates New Lexical Environments
What you'll learn: How each function declaration automatically creates its own scope layer that can "see" variables from outer scopes.
The Core Idea
Every time you declare a function in JavaScript, you're not just creating reusable code—you're creating a brand new lexical environment. This environment acts like a private workspace where the function can:
- Define its own local variables
- Access variables from the outer scope where it was defined
- Keep those references alive even after the outer scope finishes executing
Think of it like nested folders on your computer. A subfolder can "see" files in its parent folder, but the parent can't see files inside the subfolder. Each function is like creating a new subfolder in the scope chain.
How It Works
When JavaScript encounters a function declaration, it creates a new scope layer at that position in your code. This layer captures references to all variables in the surrounding (outer) scope:
let outerVar = "I'm outside";
function myFunction() {
let innerVar = "I'm inside";
console.log(outerVar); // Can access outer scope
console.log(innerVar); // Can access own scope
}
// console.log(innerVar); // Error! Can't reach inside function
Each function gets its own environment, even if multiple functions are declared in the same outer scope—they each have separate "workspaces" but share access to the parent scope.
Key Takeaway: Every function declaration creates a new lexical environment that forms a layer in the scope chain, capturing references to outer variables while keeping its own variables private.