0
0
JavascriptConceptBeginner · 3 min read

Decorator Pattern in JavaScript: What It Is and How It Works

The decorator pattern in JavaScript is a way to add new features or behavior to an object or function without changing its original code. It works by wrapping the original object or function inside another function or object that adds the extra behavior.
⚙️

How It Works

Imagine you have a plain coffee, but you want to add milk or sugar without changing the coffee itself. The decorator pattern works the same way in JavaScript: it wraps an existing object or function with another one that adds new features.

This wrapping is done by creating a new function or object that calls the original one and then adds something extra before or after. This way, the original code stays clean and unchanged, but you get new behavior.

It’s like putting a gift inside a decorated box. The gift is the original object, and the box adds style or extra features without touching the gift itself.

💻

Example

This example shows a simple function that says hello, and a decorator that adds excitement by adding exclamation marks.

javascript
function sayHello() {
  return 'Hello';
}

function excitedDecorator(originalFunction) {
  return function() {
    const result = originalFunction();
    return result + '!!!';
  };
}

const excitedSayHello = excitedDecorator(sayHello);
console.log(excitedSayHello());
Output
Hello!!!
🎯

When to Use

Use the decorator pattern when you want to add features to functions or objects without changing their original code. This is helpful when you want to keep your code clean and flexible.

For example, you can use decorators to add logging, timing, or validation to functions. In user interfaces, decorators can add styles or behaviors to components without rewriting them.

Key Points

  • The decorator pattern wraps original code to add new behavior.
  • It keeps the original code unchanged and clean.
  • It is useful for adding features like logging, styling, or validation.
  • Decorators can be functions or objects that enhance others.

Key Takeaways

The decorator pattern adds new behavior by wrapping existing functions or objects.
It helps keep original code clean and unchanged while extending functionality.
Use it to add features like logging, validation, or UI enhancements without rewriting code.
Decorators are flexible and can be stacked to combine multiple behaviors.