JavaScript › Design Patterns in JavaScript
What is the Command pattern and where is it useful in JavaScript apps?
AdvancedAnswer
Command encapsulates an action (and its parameters) as an object with a consistent execute() method, so actions can be queued, logged, undone, or passed around independently of the code that triggers them.
class AddItemCommand {
constructor(cart, item) { this.cart = cart; this.item = item; }
execute() { this.cart.push(this.item); }
undo() { this.cart.pop(); }
}Real-world example Implementing undo/redo functionality in a drawing or text-editing application.