Module-Pattern | Javascript Design Pattern Simplified | Part 4

Aakash Kumar - Jul 2 - - Dev Community

As a developer, understanding various JavaScript design patterns is crucial for writing maintainable, efficient, and scalable code. Here are some essential JavaScript design patterns that you should know:

Module Pattern

The Module pattern allows you to create public and private methods and variables, helping to keep code clean and encapsulated.

Example:

`const Module = (function() {
let privateVar = 'I am private';

function privateMethod() {
console.log(privateVar);
}

return {
publicMethod: function() {
privateMethod();
}
};
})();

Module.publicMethod(); // I am private`

Real World Example

Shopping Cart

Real-World Scenario: Implementing a shopping cart module where only public methods for adding and removing items are exposed.

Define the Module:

const CartModule = (function() {
  let cart = [];

  function addItem(item) {
    cart.push(item);
    console.log(`${item} added to cart`);
  }

  function removeItem(item) {
    cart = cart.filter(cartItem => cartItem !== item);
    console.log(`${item} removed from cart`);
  }

  function getItems() {
    return cart;
  }

  return {
    addItem,
    removeItem,
    getItems
  };
})();
Enter fullscreen mode Exit fullscreen mode

Use the Module:

CartModule.addItem('Laptop');
CartModule.addItem('Phone');
console.log(CartModule.getItems()); // ['Laptop', 'Phone']
CartModule.removeItem('Phone');
console.log(CartModule.getItems()); // ['Laptop']
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding these design patterns and knowing when to apply them can greatly improve your coding skills and make you a more effective full-stack developer. They help in creating robust and maintainable code.

Mastering these patterns will help you build better software.

Happy Coding! 🧑‍💻

Connect with Me 🙋🏻: LinkedIn

. . . . . . .