# Decorator

> The Decorator design pattern allows dynamically adding behavior or responsibilities to an object without altering its code.

## What is the Decorator design pattern?

The design pattern that allows for the extension of an object's behavior at runtime. It adds new functionality to an object by wrapping it in another object that provides the added behavior.

- Topic: Structural Patterns
- Type: design pattern

## Example

Wrong:

```js
function withLogging(fn) {
  return (...args) => {
    console.log(fn.name, args);
    fn(...args);
  };
}
```

Right:

```js
function withLogging(fn) {
  return (...args) => {
    console.log(fn.name, args);
    return fn(...args);
  };
}
```

The wrapper must return the wrapped result, or every decorated function silently returns `undefined`.

## Common mistakes

- A wrapper that forgets to return the result, so the function returns `undefined`.
- Timing an async function without `await`, so the measurement ends before the work does.

## Key points

- The wrapper returns the wrapped function's result and passes all arguments through.
- The wrapper keeps the same interface as the original, so decorators can be stacked.
- Async functions are awaited inside the wrapper when it runs code after the call.

## Interview questions

### Is the Decorator pattern the same as TypeScript decorators?

No. TypeScript `@decorator` is syntax for wrapping classes and members. It can implement the pattern, but the pattern also works with plain wrapper functions.

### Decorator vs inheritance: when should I use which?

Use a decorator to add behavior to individual objects at runtime or to combine features freely. Inheritance fixes behavior at class definition and grows a class per combination.

### Are higher-order components decorators?

Yes, in spirit. A higher-order component wraps a component and returns a new one with extra props or behavior, keeping the same rendering interface.

## Related cards

- [Decorators](https://wonderium.dev/ts/decorators.md)
- [HOCs](https://wonderium.dev/react/hocs.md)
- [Proxy](https://wonderium.dev/engineering/proxy.md)
- [Adapter](https://wonderium.dev/engineering/adapter.md)
- [Open-Closed](https://wonderium.dev/engineering/open-closed.md)

---

- Level: [Engineering](https://wonderium.dev/engineering.md)
- HTML version: https://wonderium.dev/engineering/decorator
- Last updated: 2026-11-25
