JavaScriptMedium
What is the Decorator pattern and how is it used?
By FrontendPro Editorial Team Updated 8/8/2026
#JavaScript
Answer
The Decorator pattern is a structural design pattern that allows behavior to be added to individual objects, dynamically, without affecting the behavior of other objects from the same class. It is used to extend the functionalities of objects by wrapping them with additional behavior. In JavaScript, this can be achieved using higher-order functions or classes.
For example, if you have a Car class and you want to add features like GPS or Sunroof without modifying the Car class itself, you can create decorators for these features.
js
class Car {
drive() {
return "Driving";
}
}
class CarDecorator {
constructor(car) {
this.car = car;
}
drive() {
return this.car.drive();
}
}
class GPSDecorator extends CarDecorator {
drive() {
return `${super.drive()} with GPS`;
}
}
const myCar = new Car();
const myCarWithGPS = new GPSDecorator(myCar);
console.log(myCarWithGPS.drive()); // "Driving with GPS"
