Module Scope
20 January, 2023
3
3
0
Contributors
In JavaScript, modules have a separate scope distinct from the global scope. This means that variables, functions, and other codes defined within a module are not accessible to code in other modules or the global scope unless explicitly exported. This helps to prevent naming conflicts and makes it easier to organize and reuse code.
When you import a module, the imported code is only available within the scope of the module where it is imported. For example, if you import a module into a function, the imported code will only be accessible within that function and will not be accessible outside of it.
You can also use export
and import
statement to re-export a module.
// moduleA.js
export const x = 1;
// moduleB.js
export { x } from './moduleA.js';
In the above example, moduleB.js
is re-exporting x
from moduleA.js
. This allows other modules to use x
as if it was defined in moduleB.js
.
It's important to note that JavaScript modules are singletons, meaning that a module is only loaded once, and the same instance is used throughout the application. This can be an important consideration when working with stateful modules.
Using multiple module scoping in JavaScript makes the code more structured, easy to maintain and reusable, which is the key advantage of modules.