0

I couldn't find much documentation explaining this. In JS:

// fileA.js
const varA = 1

// fileB.js
console.log(varA)

In HTML, if it looks like:

<script defer src='./fileA.js'></script>
<script defer src='./fileB.js'></script>

Then it will print '1', but if in HTML, the script tag is changed to

<script defer type='module' src='./fileA.js'></script>
<script defer src='./fileB.js'></script>

Then varA will not be found. Why is this? The workaround is to use window.varA but not sure the logic behind this phenomenon.

Thanks!

David Min
  • 1,246
  • 8
  • 27
  • It’s module-scoped. – Sebastian Simon Apr 06 '22 at 23:16
  • 1
    Why? because it's how es modules are designed. You may as well ask why you need to put function call arguments in `()`, not all languages need that, but javascript does because that's how it was designed - as for the logic behind it. It's so that modules don't need to be concerned with variables that may be declared in other modules - it's one of the main reasons modules exist, modular code – Bravo Apr 06 '22 at 23:53

0 Answers0