Skip to content

Commit a917f9c

Browse files
committed
minor fixes
1 parent ffa79a8 commit a917f9c

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

1-js/13-modules/01-modules-intro/article.md

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -81,19 +81,24 @@ Modules always work in strict mode. E.g. assigning to an undeclared variable wil
8181

8282
Each module has its own top-level scope. In other words, top-level variables and functions from a module are not seen in other scripts.
8383

84-
In the example below, two scripts are imported, and `hello.js` tries to use `user` variable declared in `user.js`, and fails (you'll see the error in the console):
84+
In the example below, two scripts are imported, and `hello.js` tries to use `user` variable declared in `user.js`. It fails, because it's a separate module (you'll see the error in the console):
8585

8686
[codetabs src="scopes" height="140" current="index.html"]
8787

88-
Modules are expected to `export` what they want to be accessible from outside and `import` what they need.
88+
Modules should `export` what they want to be accessible from outside and `import` what they need.
8989

90-
So we should import `user.js` into `hello.js` and get the required functionality from it instead of relying on global variables.
90+
- `user.js` should export the `user` variable.
91+
- `hello.js` should import it from `user.js` module.
92+
93+
In other words, with modules we use import/export instead of relying on global variables.
9194

9295
This is the correct variant:
9396

9497
[codetabs src="scopes-working" height="140" current="hello.js"]
9598

96-
In the browser, independent top-level scope also exists for each `<script type="module">`:
99+
In the browser, independent top-level scope also exists for each `<script type="module">`.
100+
101+
Here are two scripts on the same page, both `type="module"`. They don't see each other's top-level variables:
97102

98103
```html run
99104
<script type="module">
@@ -108,7 +113,13 @@ In the browser, independent top-level scope also exists for each `<script type="
108113
</script>
109114
```
110115

111-
If we really need to make a window-level global variable, we can explicitly assign it to `window` and access as `window.user`. But that's an exception requiring a good reason.
116+
```smart
117+
In the case of a web browser, we can make a window-level global variable by explicitly assigning it to `window`, e.g. `window.user = "John"`.
118+
119+
Then all scripts will see it.
120+
121+
That said, making such global variables is frowned upon. Please try to avoid them.
122+
```
112123

113124
### A module code is evaluated only the first time when imported
114125

0 commit comments

Comments
 (0)