Search code examples
javascriptfunctionfunctional-programmingdecorator

What's the point of JavaScript decorators?


I googled about JavaScript decorators but I'm not sure what the difference between calling a function using a decorator and calling a function normally is.

function myFunction(text) {
  console.log(text)
}

myFunction() vs @myFunction vs @myFunction()

I have a feeling I'm more than wrong here. Can someone explain?


Solution

  • 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.