Skip to content

Commit 6064d6e

Browse files
committed
Improve answer for 'What is Module Scope in JavaScript?'
1 parent 7e9dbeb commit 6064d6e

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

README.md

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8961,24 +8961,34 @@ The `globalThis` property provides a standard way of accessing the global object
89618961
3. Variables and functions need to be explicitly exported to be used in other modules
89628962
4. The global scope cannot access module variables unless they are explicitly exported and imported
89638963
5. Modules are always executed in strict mode
8964-
8965-
```javascript
8966-
// moduleA.js
8967-
const privateVariable = "I am private";
8968-
export const publicVariable = "I am public";
8964+
8965+
```javascript
8966+
// moduleA.js
89698967

8970-
export function publicFunction() {
8971-
console.log(privateVariable); // Works - can access private variables
8972-
return "Public function";
8973-
}
8968+
// This variable is PRIVATE to moduleA. It's like a tool inside a closed box.
8969+
const privateVariable = "I am private";
89748970

8975-
// moduleB.js
8976-
import { publicVariable, publicFunction } from './moduleA.js';
8971+
// This variable is PUBLIC because it's exported. Others can use it when they import moduleA.
8972+
export const publicVariable = "I am public";
89778973

8978-
console.log(publicVariable); // "I am public"
8979-
console.log(privateVariable); // ReferenceError: privateVariable is not defined
8980-
8981-
```
8974+
// PUBLIC function because it's exported. But it can still access privateVariable inside moduleA.
8975+
export function publicFunction() {
8976+
console.log(privateVariable); // ✅ This works because we're inside the same module.
8977+
return "Hello from publicFunction!";
8978+
}
8979+
8980+
// moduleB.js
8981+
8982+
// Importing PUBLIC items from moduleA.
8983+
import { publicVariable, publicFunction } from './moduleA.js';
8984+
8985+
console.log(publicVariable); // ✅ "I am public" - Works because it's exported.
8986+
console.log(publicFunction()); // ✅ "Hello from publicFunction!" - Works as well.
8987+
8988+
// ❌ This will cause an ERROR because privateVariable was NOT exported from moduleA.
8989+
// console.log(privateVariable); // ❌ ReferenceError: privateVariable is not defined
8990+
8991+
```
89828992
Common use cases and benefits:
89838993
89848994
- Encapsulation of module-specific code

0 commit comments

Comments
 (0)