What's the point of JavaScript decorators?

Decorators are used to literally decorate a function.

Let's say you want to type your own decorator which can be used to see how much time a function needs to run. You could write a decorator @time() that does just that. When you are done, you can use this decorator before every function you want to track.

Decorators are used as high-order functions, mainly to have a functional composition of your code!

A nice example would be a @Component() decorator in Angular. Whilst using this decorator before your class, Angular knows it has to handle it as a component and does a couple of methods with it behind the scenes.


Decorators are there to enable separation of concerns. Consider the following function:

function add(a, b) {
  return a + b;
}

Which is all well and dandy. But let's say that you want to add logging:

function add(a, b) {
  const sum = a + b;
  console.log(a, b, sum);
}

Now the function is longer and more complicated and conflates two things (summing and logging) that really don't have any relation. A better way to do it would be this:

function logs(f) {
  return function(...args) {
    const result = f(...args);
    console.log(args, result);
    return result;
  };
};

const addAndLog = logs(add);

And that's what a decorator is. What you're talking about (i.e. the JavaScript decorator proposal) is just a syntactic shortcut for the pattern above. Here logs is a decorator that adds a capability to the passed in function, the ability to log without having to complicate the function with a lot of extraneous code. The proposal is at the moment restricted to classes and methods, but I find it conceptually easier to explain with normal functions.