Command Pattern Implementation in JavaScript
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
- ✓Command Pattern runs in O(1) time and O(n) space, in JavaScript as in every other language.
- ✓A closure is the command and an array of them is the stack. For the data form, a plain object with a type discriminator plus a reducer is the shape Redux popularised and it is the reason that library could offer time-travel debugging: actions are serialisable so the whole history can be replayed.
- ✓Make persisted or replayable commands plain serialisable objects and keep closures for in-memory queues only; a reviewer will ask how the undo stack survives a reload, and closures do not.
- ✓The JavaScript trap: A command that captures a reference to mutable state records the reference, not the value, so by the time undo runs the captured object may already have changed and the undo restores whatever it holds now rather than what it held then.
- ✓Each closure allocates a function object plus a context holding the captured variables, so a long undo history of closures retains everything they captured and is a common cause of a heap that never shrinks.
What Command Pattern actually is
Command Pattern in JavaScript: what you actually reach for
JavaScript implementation
// DATA commands: serialisable, so history survives a reload and can be replayed.
const commands = [];
function makeSet(store, key, value) {
return { type: 'set', key, value, prev: store[key] }; // SNAPSHOT the old value now
}
function apply(store, cmd) {
if (cmd.type === 'set') store[cmd.key] = cmd.value;
}
function revert(store, cmd) {
if (cmd.type === 'set') store[cmd.key] = cmd.prev;
}
const store = { a: 1 };
const c = makeSet(store, 'a', 2);
apply(store, c); commands.push(c);
revert(store, commands.pop()); // store.a is 1 again
localStorage.setItem('history', JSON.stringify(commands)); // impossible with closures
// Async undo must be SERIALISED or two undos interleave.
let chain = Promise.resolve();
const enqueue = (fn) => (chain = chain.then(fn, fn));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 FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Command Pattern?
A closure is the command and an array of them is the stack. For the data form, a plain object with a type discriminator plus a reducer is the shape Redux popularised and it is the reason that library could offer time-travel debugging: actions are serialisable so the whole history can be replayed. structuredClone snapshots state alongside a command, and queueMicrotask or setTimeout schedules deferred execution. AbortController is the standard cancellation token to hand to a long-running command.
What is the most common JavaScript mistake when implementing Command Pattern?
A command that captures a reference to mutable state records the reference, not the value, so by the time undo runs the captured object may already have changed and the undo restores whatever it holds now rather than what it held then. This produces an undo that appears to work and silently corrupts history, and it is far more common than a crash. Snapshot the values you need at construction, with structuredClone if they are objects. Async commands add a second problem: an undo stack that awaits can interleave, so two undos in flight apply out of order unless the stack is serialised through a promise chain.
How does Command Pattern actually perform in JavaScript?
Each closure allocates a function object plus a context holding the captured variables, so a long undo history of closures retains everything they captured and is a common cause of a heap that never shrinks. Plain-object commands are small, and the state they reference can be structurally shared instead of deep-copied. Storing full state snapshots per command is simple and turns memory into O(history times state), which is why the command-plus-inverse form is preferred once state is large. Time complexity is O(1) and space is O(n).
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 trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.