What is the decorator pattern?

JavaScript

The short answer

The decorator pattern adds new behavior to an object without modifying it. You wrap the original object with a decorator that adds functionality on top. The original object stays unchanged, and you can stack multiple decorators to add more features. In JavaScript, higher-order functions and higher-order components (HOCs) follow this pattern.

How it works

function withLogging(fn) {
return function (...args) {
console.log(`Calling ${fn.name} with`, args);
const result = fn(...args);
console.log(`Result:`, result);
return result;
};
}
function add(a, b) {
return a + b;
}
const loggedAdd = withLogging(add);
loggedAdd(2, 3);
// "Calling add with [2, 3]"
// "Result: 5"

withLogging is a decorator. It wraps add with extra logging behavior. The original add function is not modified.

Real-world examples

Adding retry logic to a fetch function:

function withRetry(fn, maxRetries = 3) {
return async function (...args) {
for (
let attempt = 1;
attempt <= maxRetries;
attempt++
) {
try {
return await fn(...args);
} catch (error) {
if (attempt === maxRetries) throw error;
console.log(
`Attempt ${attempt} failed, retrying...`
);
}
}
};
}
const fetchWithRetry = withRetry(fetch, 3);

React higher-order components (HOCs):

function withAuth(Component) {
return function AuthenticatedComponent(props) {
const { user } = useAuth();
if (!user) return <LoginPage />;
return <Component {...props} user={user} />;
};
}
const ProtectedDashboard = withAuth(Dashboard);

withAuth decorates Dashboard by adding authentication checking. The original Dashboard component does not change.

Stacking decorators

You can apply multiple decorators:

const enhancedFetch = withRetry(
withLogging(withTimeout(fetch, 5000)),
3
);

Each decorator adds one behavior. They compose together cleanly.

Interview Tip

The simplest way to explain this is with a higher-order function example. Show a function that takes a function and returns a new function with added behavior. Then connect it to React HOCs if the interview is React-focused. The key point is that the original object/function is not modified.

Why interviewers ask this

The decorator pattern shows up constantly in JavaScript — higher-order functions, middleware, HOCs, and function composition all use this pattern. Interviewers want to see if you recognize the pattern and can apply it to add functionality cleanly without modifying existing code.