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
};
})();
Use the Module:
CartModule.addItem('Laptop');
CartModule.addItem('Phone');
console.log(CartModule.getItems()); // ['Laptop', 'Phone']
CartModule.removeItem('Phone');
console.log(CartModule.getItems()); // ['Laptop']
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
Top comments (2)
Should getItems be public? As written it looks like it allows direct access to the internal cart. I would expect getItems to return a copy of the cart that can't be used to manipulate the items in cart.
Different ways to achieve same result:
Or (less code again):
Kinda not usual, just noodling around with alternatives 🙂
But, of course, none of this is really necessary these days as we have native ES modules.