Blog>
Snippets

Using module for namespacing

Create an example where the module is used to create a namespace to avoid global scope pollution.
// myNamespaceModule.js
// This module defines a namespace 'myNamespace' and attaches functions to it
const myNamespace = (function() {
    // Private variable
    const privateVar = 'I am private';
    
    // Public API
    return {
        publicMethod: function() {
            console.log('Hello from the public method!');
        },
        getPrivate: function() {
            console.log(privateVar);
        }
    };
})();

// Export the namespace
export { myNamespace };
Defines a module that encapsulates its functionality within the 'myNamespace' object to avoid polluting the global scope. This module has a private variable and exposes a public API.
// main.js
// This script imports the namespace module and uses its public API

// Import the namespace object from the module
import { myNamespace } from './myNamespaceModule.js';

// Using the public methods of the namespace
myNamespace.publicMethod(); // Logs 'Hello from the public method!'
myNamespace.getPrivate(); // Logs 'I am private'
Imports the 'myNamespace' from 'myNamespaceModule.js' and uses its public methods to demonstrate namespacing.