|
518 | 518 | | 468 | [How to find the number of parameters expected by a function?](#how-to-find-the-number-of-parameters-expected-by-a-function) |
|
519 | 519 | | 469 | [What is globalThis, and what is the importance of it?](#what-is-globalthis-and-what-is-the-importance-of-it) |
|
520 | 520 | | 470 | [What are the array mutation methods?](#what-are-the-array-mutation-methods) |
|
| 521 | +| 471 | [What is module scope in JavaScript?](#what-is-module-scope-in-JavaScript) | |
| 522 | + |
521 | 523 | <!-- TOC_END -->
|
522 | 524 |
|
523 | 525 | <!-- QUESTIONS_START -->
|
@@ -8950,8 +8952,47 @@ The `globalThis` property provides a standard way of accessing the global object
|
8950 | 8952 |
|
8951 | 8953 | **[⬆ Back to Top](#table-of-contents)**
|
8952 | 8954 |
|
| 8955 | +471. ### What is module scope in JavaScript? |
| 8956 | + 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. |
| 8957 | +
|
| 8958 | + Key characteristics of module scope: |
| 8959 | +
|
| 8960 | + 1. Variables declared in a module are scoped to that module only. |
| 8961 | + 2. Each module has its own top-level scope |
| 8962 | + 3. Variables and functions need to be explicitly exported to be used in other modules |
| 8963 | + 4. The global scope cannot access module variables unless they are explicitly exported and imported |
| 8964 | + 5. Modules are always executed in strict mode |
| 8965 | + |
| 8966 | + ```javascript |
| 8967 | + // moduleA.js |
| 8968 | + const privateVariable = "I am private"; |
| 8969 | + export const publicVariable = "I am public"; |
| 8970 | + |
| 8971 | + export function publicFunction() { |
| 8972 | + console.log(privateVariable); // Works - can access private variables |
| 8973 | + return "Public function"; |
| 8974 | + } |
| 8975 | + |
| 8976 | + // moduleB.js |
| 8977 | + import { publicVariable, publicFunction } from './moduleA.js'; |
| 8978 | + |
| 8979 | + console.log(publicVariable); // "I am public" |
| 8980 | + console.log(privateVariable); // ReferenceError: privateVariable is not defined |
| 8981 | + |
| 8982 | + ``` |
| 8983 | + Common use cases and benefits: |
| 8984 | +
|
| 8985 | + - Encapsulation of module-specific code |
| 8986 | + - Prevention of global scope pollution |
| 8987 | + - Better code organization and maintenance |
| 8988 | + - Explicit dependency management |
| 8989 | + - Protection of private implementation details |
| 8990 | +
|
| 8991 | +**[⬆ Back to Top](#table-of-contents)** |
| 8992 | +
|
8953 | 8993 | <!-- QUESTIONS_END -->
|
8954 | 8994 |
|
| 8995 | +
|
8955 | 8996 | ### Coding Exercise
|
8956 | 8997 |
|
8957 | 8998 | #### 1. What is the output of below code
|
|
0 commit comments