Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the execution context of a module in JavaScript? How do I access it explicitly in the browser's console?

Tags:

javascript

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?

like image 432
shellwhale Avatar asked Nov 24 '25 11:11

shellwhale


1 Answers

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.

like image 180
Bergi Avatar answered Nov 25 '25 23:11

Bergi