Member-only story
The Power of Memento Design Pattern in JavaScript
Remember your mementos

The Memento Pattern in programming is useful in situations where we need a way to restore an object’s state.
As a JavaScript developer, we work with this concept in many situations especially now in modern web applications.
If you’ve been developing on the web for some time then you might have heard of the term hydration.
If you don’t know what hydration is, it’s a technique in web development where the client-side takes static content which was stored in any programming language such as JSON, JavaScript, HTML, etc., and converts it into code that browsers are able to run during runtime. At that stage, JavaScript is run and is able to do things like attach event listeners when the DOM begins running on the page.
The memento pattern is similar. In this post, we are going to implement the Memento pattern for the runtime and will not be storing anything statically.
If you worked with JSON.parse
and JSON.stringify
chances are you might have accidentally implemented a memento before.
Usually, there are three objects that implement the full flow of the Memento pattern:
- Originator
- Memento
- Caretaker
The Originator defines the interface that triggers the creation and storing of itself as the memento.
The Memento is the internal state representation of the Originator that is passed and retrieved from the Caretaker.
The Caretaker has one job: to store or save the memento to be used later. It can retrieve the memento it stored but it does not mutate anything.
Implementing the Memento Design Pattern
Now that we described the pattern we are going to implement it to master this practice in code.
We will be creating an interactive email input field as a DOM element. We are going to add one smart behavior to our input field so that our user will immediately become aware that they need to add the @
symbol before submitting.