JavaScript Programming

JavaScript Decorators

A decorator can add behavior to a class or one of its elements without crowding the code that defines its core purpose. In JavaScript, decorators offer a compact way to register, validate, or instrument class features—but the syntax is only the surface. Understanding what a decorator receives, what it may return, and which decorator model your tools support is essential before putting one to work.

At Decorators.cc, we usually explore how thoughtful additions can shape a space without obscuring its structure. The programming meaning is different, but the useful question is familiar: what is being changed, and does the change make the whole easier to understand? This guide introduces the modern JavaScript decorator model, practical examples, and its important differences from TypeScript’s older experimental implementation.

What a JavaScript decorator does

A decorator is a function applied to a class or class element—such as a method, field, getter, setter, or auto-accessor. It can inspect the element’s value and context, then return a replacement or, for certain element kinds, arrange additional initialization behavior.

The familiar @ notation makes the application concise. Conceptually, a decorator is still a function participating in class definition; it is not a special kind of object or a general-purpose wrapper automatically placed around every use of a method.

Keep in mind: Decorator support depends on the JavaScript runtime, transpiler, and toolchain. The standardized decorator proposal and TypeScript’s legacy experimental decorators are distinct models, even when their source code looks similar.

The modern decorator model

In the current standardized proposal, a decorator is called with two arguments: the element’s value and a context object. The value depends on what is decorated. For a method, it is the method function; for a field, it is initially undefined. The context describes the element, including its kind and name, and offers capabilities that vary by element type.

A decorator may return a replacement value when that kind of element permits one. A method decorator, for example, can return another function to replace the original method. A field decorator can return an initializer function that transforms the value when each instance is created. Class decorators can return a replacement class.

Decorators are evaluated as part of defining a class, while some returned initializer functions run later as instances are initialized. That distinction matters: definition-time work and per-instance work happen at different moments.

A method decorator for registration

A small registry is one way to see the modern method-decorator shape. Here, each decorated method is recorded by name when its class is defined:

const actions = new Map();

function register(value, context) {
  if (context.kind !== "method") {
    throw new TypeError("@register can only decorate methods");
  }

  actions.set(String(context.name), value);
}

class RoomActions {
  @register
  refreshPalette() {
    return "Palette refreshed";
  }
}

The decorator receives the method function as value and a context that identifies it as a method and provides its name. This example records the original function; it does not replace the method or change how calls on RoomActions instances behave.

In a larger system, a registry might connect commands to a menu or a framework might discover handlers during class definition. The pattern is useful when registration is genuinely part of the class’s declaration. If there are only one or two entries, an explicit map may be easier to follow.

Wrapping a method safely

A method decorator can also return a wrapper. Use a regular function when the wrapper must preserve the call-time this value:

function logged(value, context) {
  if (context.kind !== "method") {
    throw new TypeError("@logged can only decorate methods");
  }

  return function (...args) {
    console.log(`Calling ${String(context.name)}`);
    return value.call(this, ...args);
  };
}

class RoomActions {
  @logged
  refreshPalette() {
    return "Palette refreshed";
  }
}

The wrapper delegates to the original method with value.call(this, ...args), retaining the receiver and arguments. An arrow function would capture this from its surrounding scope instead, which is generally not what a method wrapper needs.

This example logs before the method runs. Production logging may also need to handle thrown errors or asynchronous results. Add those behaviors deliberately rather than assuming a short wrapper covers every execution path.

Validating a field’s initial value

Field decorators can return an initializer that checks or transforms the value supplied for each instance. The following example accepts only positive numbers:

function positive(value, context) {
  if (context.kind !== "field") {
    throw new TypeError("@positive can only decorate fields");
  }

  return function (initialValue) {
    if (typeof initialValue !== "number" || initialValue <= 0) {
      throw new RangeError(`${String(context.name)} must be positive`);
    }

    return initialValue;
  };
}

class RoomPlan {
  @positive
  area = 24;
}

The returned function runs during instance initialization with the field’s initial value. This example validates that initial value; it does not automatically intercept later assignments. For ongoing validation, use an accessor or setter, a dedicated update method, or another mechanism that clearly covers every write.

When designing a decorator, be precise about its boundary. A check that runs once at construction is different from a guarantee that a value will remain valid throughout an object’s lifetime.

Decorators with arguments

To configure a decorator, use a function that returns the decorator. The outer function receives the option; the inner function receives the decorated element and its context:

function tagged(label) {
  return function (value, context) {
    if (context.kind !== "method") {
      throw new TypeError("@tagged can only decorate methods");
    }

    console.log(`Registering ${label}: ${String(context.name)}`);
  };
}

class RoomActions {
  @tagged("design")
  refreshPalette() {
    return "Palette refreshed";
  }
}

Here, tagged("design") creates the decorator that is applied to the method. This two-step shape separates configuration from element handling, but it also adds another layer to read. Use it when the option makes the behavior meaningfully reusable or adaptable.

Decorator order and composition

More than one decorator can be applied to the same element. They are evaluated in source order, from top to bottom, and their returned replacements are applied in reverse order, from bottom to top. With decorators named first and second, the result is effectively first(second(method)).

This resembles a sequence of finishing decisions: the order in which transformations are written and the order in which their effects are layered are related, but not identical. When decorators interact, make the sequence visible in names and tests. Avoid relying on side effects that are difficult to trace.

Standard decorators and TypeScript legacy decorators

JavaScript’s standardized decorator model should not be confused with TypeScript’s legacy experimental decorators. In the standard model, a decorator typically receives (value, context). Legacy TypeScript method decorators commonly receive the target, property key, and property descriptor instead. The arguments, available features, and behavior are not interchangeable.

TypeScript projects using the legacy implementation generally enable experimentalDecorators in their compiler configuration. Standard-decorator support depends on the TypeScript version and configuration in use. Check the documentation for the exact compiler, framework, and runtime combination before adopting syntax in a project.

Decorators have long appeared in language proposals, transpilers, and frameworks before becoming a standardized JavaScript feature. That history explains why examples found online may describe different APIs. Treat the version and toolchain as part of the example, not as incidental setup.

Common pitfalls to avoid

  • Assuming universal support: Confirm that the runtime or build pipeline understands the decorator syntax and model you intend to use.
  • Mixing APIs: Do not pass standard-model examples into a legacy TypeScript decorator setup, or assume legacy descriptor patterns work unchanged with standard decorators.
  • Forgetting the receiver: A method wrapper should preserve this when calling the original method.
  • Confusing initialization with assignment: A field initializer does not, by itself, validate every later change to that field.
  • Hiding too much behavior: A decorator that changes control flow, stores global state, and transforms values all at once can make a class harder to reason about.
  • Ignoring definition-time effects: Decorator expressions and decorator functions can run while a class is being defined, so keep such work predictable and intentional.

When a decorator is the right tool

Decorators are most helpful when a behavior is repeatable, naturally belongs beside a class element, and can be explained with a small, clear contract. Registration, instrumentation, and carefully scoped initialization logic can fit that description.

A helper function, explicit method call, or ordinary wrapper may be clearer when behavior is local, needs frequent configuration, or is surprising to readers. The goal is not to make code shorter at any cost. It is to make an addition legible without obscuring the work the class is meant to do.

As with arranging a room, every layer should earn its place: the structure remains primary, and additions should support how the whole is used. For more on the related Python concept, see Python Decorators.

A practical checklist

  1. Identify the decorator model supported by your runtime and toolchain.
  2. Decide whether the target is a class, method, field, or another supported class element.
  3. Write down what the decorator receives, what it returns, and when any added behavior runs.
  4. Preserve method call behavior, including this, arguments, return values, and errors where relevant.
  5. Test decorated and undecorated behavior, including multiple instances and decorator composition.
  6. Prefer the simplest mechanism that makes the behavior easy for the next reader to understand.

Theme