Skip to content

Commit fcb0fdb

Browse files
committed
Added new JavaScript questions and solutions to README.md
1 parent b13c320 commit fcb0fdb

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,8 @@
518518
| 468 | [How to find the number of parameters expected by a function?](#how-to-find-the-number-of-parameters-expected-by-a-function) |
519519
| 469 | [What is globalThis, and what is the importance of it?](#what-is-globalthis-and-what-is-the-importance-of-it) |
520520
| 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+
521523
<!-- TOC_END -->
522524

523525
<!-- QUESTIONS_START -->
@@ -8950,8 +8952,47 @@ The `globalThis` property provides a standard way of accessing the global object
89508952
89518953
**[⬆ Back to Top](#table-of-contents)**
89528954
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+
89538993
<!-- QUESTIONS_END -->
89548994
8995+
89558996
### Coding Exercise
89568997
89578998
#### 1. What is the output of below code

0 commit comments

Comments
 (0)