Javascript Modules, the Browser Debugger and the Object or Variable Lifecycle

Suppose the following simple code:

class Sample {}
const sample = new Sample();

In case I load it as:

<script type="text/javascript" src="sample.js"></script>

Then if I check in the browser’s console for the instance object sample , it does return the in memory value: Sample {}

In case I load it as a Module:

<script type="module" src="sample.js"></script>

When I check the browser’s console, I got the Uncaught ReferenceError: sample is not defined

Is it a common behaviour when using Modules?

Yes, that is how it is supposed to work. The first situation demonstrates that the global namespace has become polluted.

One of the benefits of using modules is that it helps to protect against polluting the global namespace, which is why you couldn’t find it from the browser console.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.