Advertisement
Advanced JavaScript, Design Patterns in JavaScript

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

Short 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.

Save JavaScript mock interview
Advertisement
AModel 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.
Likely follow-ups
  • How does Command relate to Redux-style actions and reducers?
Related topics