Singleton ensures one instance; Factory abstracts object creation; Constructor vs Factory is an architectural choice. This article compares all three with runnable examples and explains when each makes sense in JavaScript.
Prerequisites: JS Foundations #3 — Closures
1. Singleton — One Instance, Guaranteed
Loading editor...
Closure-based singleton:
Loading editor...
2. Factory Function — Create Objects Without new
Factory functions hide creation complexity and can return different implementations:
Loading editor...
3. Constructor Function vs Factory Function
Loading editor...
4. When to Use Which
Loading editor...
Key Takeaways
- Singleton: one instance — ESM modules are natural singletons; closures can enforce it.
- Factory: creates objects without
new— can return different shapes, hide implementation, use true private state. - Constructor: needs
new— has prototype chain,instanceof, shared methods (memory efficient). - In modern JS, factories + closures often replace constructors — composition over inheritance.
- Use the pattern that fits the problem, not the pattern you're most comfortable with.
Next: Data Structures #1 — Linked List — implement singly and doubly linked lists with all operations.
