Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Memento Pattern Implementation in JavaScript

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Memento Pattern runs in O(1) time and O(n) space, in JavaScript as in every other language.
  • ✓structuredClone is the built-in deep snapshot and handles cycles, Map, Set, Date, RegExp and typed arrays, which is everything the JSON round trip loses.
  • ✓Snapshot with structuredClone and freeze the result, so an accidental write to a stored memento throws in strict mode instead of corrupting history silently.
  • ✓The JavaScript trap: Freezing is shallow, so Object.freeze on a snapshot with nested objects leaves every nested object writable and the protection is an illusion; a recursive freeze is needed and it is not free.
  • ✓structuredClone walks the whole graph, so per-keystroke snapshots of a large document are the classic cause of an editor stuttering; the cost is proportional to state size and independent of how much changed.

What Memento Pattern actually is

Memento captures an object internal state so it can be restored later, without exposing that state to the code holding the snapshot. Undo, checkpointing and transaction rollback are all this pattern. The interesting question is never how to store the snapshot but how to take one that is genuinely independent of the live object, which is the deep-versus-shallow copy problem again, and how to store it without either exploding memory or opening a security hole. Two languages here give you independence for free because their values copy on assignment. Two ship a serialisation mechanism that solves it and is now formally discouraged, in one case because it executes arbitrary code on restore and in the other because it was removed from the runtime outright. And one makes the classic aliasing bug a compile error.

Memento Pattern in JavaScript: what you actually reach for

structuredClone is the built-in deep snapshot and handles cycles, Map, Set, Date, RegExp and typed arrays, which is everything the JSON round trip loses. Object.freeze makes a captured snapshot immutable. For large histories, the standard approach is structural sharing rather than cloning, which is what Immer implements on top of Proxy: it produces a new immutable state that shares every unchanged subtree with the previous one.

JavaScript implementation

Snapshot with structuredClone and freeze the result, so an accidental write to a stored memento throws in strict mode instead of corrupting history silently. Keep the memento opaque to the caretaker by exposing only restore, not the fields. Prefer storing the inverse operation to storing full state once the state is more than a few kilobytes.
javascript
function deepFreeze(o) {
  for (const v of Object.values(o)) if (v && typeof v === 'object') deepFreeze(v);
  return Object.freeze(o);            // Object.freeze alone is SHALLOW
}

class Editor {
  #text = ''; #cursor = 0;

  save() {
    // structuredClone handles cycles, Map, Set, Date, the JSON round trip does not.
    return deepFreeze(structuredClone({ text: this.#text, cursor: this.#cursor }));
  }

  restore(m) { this.#text = m.text; this.#cursor = m.cursor; }

  type(s) { this.#text += s; this.#cursor += s.length; }
}

const ed = new Editor();
const checkpoint = ed.save();
ed.type('hello');
ed.restore(checkpoint);

// structuredClone DISCARDS the prototype: a cloned instance has data, no methods.
const clonedEditor = structuredClone(ed);   // DataCloneError: private fields / methods

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The JavaScript-specific trap

Freezing is shallow, so Object.freeze on a snapshot with nested objects leaves every nested object writable and the protection is an illusion; a recursive freeze is needed and it is not free. structuredClone throws DataCloneError on functions, DOM nodes, Error objects in older runtimes, and any class instance is cloned to a plain object with its prototype discarded, so a restored memento of a class instance has data but no methods. That failure appears only when a method is called, well after the restore.

Performance in JavaScript, beyond the O(1)

structuredClone walks the whole graph, so per-keystroke snapshots of a large document are the classic cause of an editor stuttering; the cost is proportional to state size and independent of how much changed. Structural sharing makes a snapshot proportional to the CHANGE instead, which is why every serious undo implementation ends up there. Frozen objects are also slightly slower to read in V8 in some cases because the engine must respect the immutability, though the effect is usually negligible next to the clone. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Memento Pattern between languages.

Real-World Applications

Memento Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In JavaScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Memento Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Memento Pattern appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Memento Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Memento Pattern to build pattern recognition. In JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

Frequently Asked Questions

Which JavaScript type or library should I use for Memento Pattern?

structuredClone is the built-in deep snapshot and handles cycles, Map, Set, Date, RegExp and typed arrays, which is everything the JSON round trip loses. Object.freeze makes a captured snapshot immutable. For large histories, the standard approach is structural sharing rather than cloning, which is what Immer implements on top of Proxy: it produces a new immutable state that shares every unchanged subtree with the previous one.

What is the most common JavaScript mistake when implementing Memento Pattern?

Freezing is shallow, so Object.freeze on a snapshot with nested objects leaves every nested object writable and the protection is an illusion; a recursive freeze is needed and it is not free. structuredClone throws DataCloneError on functions, DOM nodes, Error objects in older runtimes, and any class instance is cloned to a plain object with its prototype discarded, so a restored memento of a class instance has data but no methods. That failure appears only when a method is called, well after the restore.

How does Memento Pattern actually perform in JavaScript?

structuredClone walks the whole graph, so per-keystroke snapshots of a large document are the classic cause of an editor stuttering; the cost is proportional to state size and independent of how much changed. Structural sharing makes a snapshot proportional to the CHANGE instead, which is why every serious undo implementation ends up there. Frozen objects are also slightly slower to read in V8 in some cases because the engine must respect the immutability, though the effect is usually negligible next to the clone. Time complexity is O(1) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what Replit offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.