Advertisement
Module scope is a feature introduced with ES6 (ES2015) modules that creates a scope specific to a module file, isolating variables and functions declared within it from the global scope and other modules. Variables and functions declared in a module are private by default and can only be accessed by other modules if they are explicitly exported.
Key characteristics of module scope:
1. Variables declared in a module are scoped to that module only.
2. Each module has its own top-level scope
3. Variables and functions need to be explicitly exported to be used in other modules
4. The global scope cannot access module variables unless they are explicitly exported and imported
5. Modules are always executed in strict mode
1// moduleA.js
2
3// This variable is PRIVATE to moduleA. It's like a tool inside a closed box.
4
5const privateVariable = "I am private";
6
7// This variable is PUBLIC because it's exported. Others can use it when they import moduleA.
8
9export const publicVariable = "I am public";
10
11// PUBLIC function because it's exported. But it can still access privateVariable inside moduleA.
12
13export function publicFunction() {
14
15console.log(privateVariable); // ✅ This works because we're inside the same module.
16
17return "Hello from publicFunction!";
18}
19
20// moduleB.js
21
22// Importing PUBLIC items from moduleA.
23
24import { publicVariable, publicFunction } from "./moduleA.js";
25
26console.log(publicVariable); // ✅ "I am public" - Works because it's exported.
27
28console.log(publicFunction()); // ✅ "Hello from publicFunction!" - Works as well.
29
30// ❌ This will cause an ERROR because privateVariable was NOT exported from moduleA.
31// console.log(privateVariable); // ❌ ReferenceError: privateVariable is not definedCommon use cases and benefits:
- Encapsulation of module-specific code
- Prevention of global scope pollution
- Better code organization and maintenance
- Explicit dependency management
- Protection of private implementation details
Advertisement
JavaScript Coding Exercise 46
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement