1

In JavaScript, using modules requires setting the value of the type attribute to module on script tags. While doing so, I noticed that I cannot access initialized variables from the browser's console. It would seem that modules have their own scope outside of the window object.

In the following snippet, I try to access window.foo while usingtype=module. This fails as it only exists in what I guess is the module's scope.

<script type="module">
    var foo = 40;
    console.log(foo); // 40
    console.log(window.foo); // undefined
</script>

Here, I try do the same thing without type="module".

<script>
    var foo = 40;
    console.log(foo); // 40
    console.log(window.foo); // 40
</script>

How can I access that scope explicitly from the global scope / browser's console?

shellwhale
  • 820
  • 1
  • 10
  • 34
  • 2
    You can't. Each module has its own scope. Only exported values can be accessed. There might be a way to switch the "context" in the browser console but that would depend on the browser (this is just a guess based on how browsers allow to do that with iframes). – Felix Kling Jun 14 '21 at 16:06

1 Answers1

1

It would seem that modules have their own scope

Yes, that's one of their major selling points.

How can I access that scope explicitly from the global scope?

You cannot - again, by design.

How can I access that scope explicitly from the browser's console?

You need to set a breakpoint on some code inside the module, where that scope is visible, or inspect a closure that comes from the module.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Could you provide an example of what you describe in your last sentence? I'd gladly accept that answer. – shellwhale Jun 16 '21 at 09:59
  • 1
    @shellwhale See [this thread](https://stackoverflow.com/q/52150979/1048572) or [some screenshots](https://www.google.com/search?q=closure+scopes+devtools&source=lnms&tbm=isch) – Bergi Jun 16 '21 at 11:21