Back to results for “Design Patterns in JavaScript”
JavaScript › Design Patterns in JavaScript

What is the Command pattern and where is it useful in JavaScript apps?

Advanced

Answer

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.

Common follow-ups: How does Command relate to Redux-style actions and reducers?