You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/13-modules/01-modules-intro/article.md
+16-5Lines changed: 16 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -81,19 +81,24 @@ Modules always work in strict mode. E.g. assigning to an undeclared variable wil
81
81
82
82
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.
83
83
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):
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:
97
102
98
103
```html run
99
104
<scripttype="module">
@@ -108,7 +113,13 @@ In the browser, independent top-level scope also exists for each `<script type="
108
113
</script>
109
114
```
110
115
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
+
```
112
123
113
124
### A module code is evaluated only the first time when imported
0 commit comments