@@ -8961,24 +8961,34 @@ The `globalThis` property provides a standard way of accessing the global object
8961
8961
3. Variables and functions need to be explicitly exported to be used in other modules
8962
8962
4. The global scope cannot access module variables unless they are explicitly exported and imported
8963
8963
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
8969
8967
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" ;
8974
8970
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 " ;
8977
8973
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
+ ` ` `
8982
8992
Common use cases and benefits:
8983
8993
8984
8994
- Encapsulation of module-specific code
0 commit comments