What is the command pattern?
JavaScriptThe short answer
The command pattern turns operations into objects. Instead of calling a function directly, you wrap it in a command object that can be stored, queued, logged, or undone. This is the pattern behind undo/redo functionality, task queues, and action histories.
How it works
class Command { execute() {} undo() {}}class AddTextCommand extends Command { constructor(editor, text) { super(); this.editor = editor; this.text = text; } execute() { this.editor.content += this.text; } undo() { this.editor.content = this.editor.content.slice( 0, -this.text.length ); }}// Usageconst editor = { content: '' };const history = [];const cmd1 = new AddTextCommand(editor, 'Hello');cmd1.execute(); // content: "Hello"history.push(cmd1);const cmd2 = new AddTextCommand(editor, ' World');cmd2.execute(); // content: "Hello World"history.push(cmd2);// Undoconst lastCmd = history.pop();lastCmd.undo(); // content: "Hello"Each command knows how to execute and how to undo itself. The history array stores all commands, making undo/redo straightforward.
A simpler JavaScript version
You do not need classes. Functions work just as well:
function createAddCommand(editor, text) { return { execute() { editor.content += text; }, undo() { editor.content = editor.content.slice( 0, -text.length ); }, };}Where you see it
- Text editors — each keystroke is a command that can be undone
- Drawing apps — each brush stroke is a command
- Form wizards — each step can be reversed
- Redux — actions are essentially commands (objects that describe operations)
- Task queues — commands can be stored and executed later
Interview Tip
The undo/redo example is the clearest way to explain this pattern. Show a command with execute and undo methods, and a history array that tracks commands. Mentioning that Redux actions follow the command pattern shows you can connect design patterns to real tools.
Why interviewers ask this
The command pattern tests if you understand how to decouple the "what to do" from the "when to do it." Interviewers want to see if you can apply this pattern to problems like undo/redo, action logging, or task queuing.