Course contentsShow
← JavaScript
Lesson 1397 of 2,72331. ModulesFree lesson

The Module Scope

Understand that each module has its own scope and top-level variables are not global.

The Module Scope

You'll learn how JavaScript modules create their own private scope, keeping variables from leaking into the global namespace.

How Module Scope Works

In traditional JavaScript files (scripts), any variable declared at the top level becomes a global variable accessible everywhere. This causes problems: naming conflicts, accidental overwrites, and code that's hard to debug.

ES modules change this completely. When you use modules (files with import or export), each module gets its own private scope. Top-level variables in a module are not global—they're local to that module. They only become available to other modules if you explicitly export them.

Think of it like apartments in a building. In the old script world, everyone shared one big room where all furniture was visible and accessible to everyone (chaos!). With modules, each apartment has its own private space. You control exactly what you share through the door (exports).

Why This Matters

// userModule.js
const userName = "Alice"; // NOT global, only exists in this module
export const greeting = "Hello";

// productModule.js  
const userName = "Bob"; // Different userName, no conflict!
// This userName is separate from the one above

Both modules can use userName without any collision because each module has its own scope. Before modules, the second declaration would have overwritten the first in the global scope.

This isolation makes code safer, more maintainable, and prevents the "global namespace pollution" that plagued older JavaScript applications.

Key Takeaway: Each ES module has its own private scope—top-level variables stay local to the module unless explicitly exported, eliminating global namespace conflicts.