Sobes.tech
Middle

Explain what the module pattern in JavaScript is and where it is used?

sobes.tech AI

Answer from AI

The module pattern allows encapsulating code by defining public and private interfaces. This is achieved by creating a private scope using Immediately Invoked Function Expressions (IIFE) or ES Modules syntax.

It is used for:

  • Encapsulation: Hides internal implementation, exposing only the necessary public API.
  • Preventing pollution of the global scope: Variables and functions remain local within the module.
  • Code organization: Breaks the application into logical blocks, making it easier to understand and maintain.
  • Code reuse: Modules can be imported and used in different parts of the application.

Example using IIFE:

// Creating a private scope
const myModule = (() => {
  // Private variable
  let privateVariable = 'I am private!';

  // Private function
  const privateMethod = () => {
    console.log(privateVariable);
  };

  // Public function
  const publicMethod = () => {
    console.log('This is a public function.');
    privateMethod(); // Access to private function
  };

  // Return only public members
  return {
    publicMethod: publicMethod
  };
})();

// Using the public interface
myModule.publicMethod(); // Will output "This is a public function." and "I am private!"
// myModule.privateVariable; // Error - not accessible
// myModule.privateMethod(); // Error - not accessible

Example using ES Modules:

// module.js
// Private variable (not exported)
const privateVariable = 'I am private in ES Module!';

// Private function (not exported)
const privateMethod = () => {
  console.log(privateVariable);
};

// Public function (exported)
export const publicMethod = () => {
  console.log('This is a public function in ES Module.');
  privateMethod();
};
// main.js
import { publicMethod } from './module.js';

publicMethod(); // Will output "This is a public function in ES Module." and "I am private in ES Module!"