Member-only story
The Power of Flyweight Design Pattern in JavaScript
Sharing is caring in JavaScript too

In JavaScript, we are fortunate to have an automatic garbage collection mechanism built into the language. There are some cases where it is essential to manage the memory ourselves. This is where the Flyweight Design Pattern can come in handy as it intends to share commonalities into objects that clients can benefit from. This is an efficient way to write scalable applications as it benefits us to allow users to consume the least amount of memory usage possible.
In this article, we will be going over the power of the Flyweight Design Pattern in JavaScript and leverage it to create more memory-efficient applications. We will go over the problems that arise and showcase how the flyweight pattern knocks them all away.
If you’ve used a JavaScript library before, there’s a good chance you’ve worked directly on some variation of a flyweight pattern given to you whether it was through a JavaScript library, framework, or even the DOM.
Let's take a look at this array of objects that represent objects as DOM elements:
If you look at the children
array, notice there are three objects that are structurally identical:

This is already an issue because if we were to continue this practice and our project grows larger our program will take a big hit in performance because it will create three separate objects in memory although they are all structurally equivalent. Imagine if there were 1,000?
When we go over real examples of the flyweight design pattern this is basically what the flyweight intends to do behind the scenes: