DEV Community

Bjorn-Donald Bassey
Bjorn-Donald Bassey

Posted on

Have you heard of function decorators

One advice we usually hear as developers is to do our very best to not repeat code. So what we do is place code which could be used numerous time in its separate function. But sometimes, it isn't so simple. Take try catch blocks for example,

try {
console.log("loading...")
// run some code
console.log("Finished.")
} catch (error) {
console.log(error)
}

JavaScript does have allocation for decorators. But there are only available for class methods and class fields. You can read more here.
But for now, we will be taking a look at a function decorators. A way to have a decorators for functions outside a class is to use higher function. This is a function that returns a function. This could be designed like a function wrapper

Say you have a function
function printText(text){
console.log(
Code says, ${text});
}

And you want to wrap this function code with the try catch block from above.

function loggingDecorator(wrappedFn) {
return function() {
try {
console.log("loading...")
// run some code
console.log("Finished.")
} catch (error) {
console.log(error)
}
}
}

You use the decorator like this
const wrapped = loggingDecorator(printText);
wrapped("have a good day.");

Thanks for reading.

Top comments (3)

Collapse
 
sabbakilam profile image
SabbaKilam

Typo: should say "... not to repeat code."

Collapse
 
6lackbjorn profile image
Bjorn-Donald Bassey

Thanks

Collapse
 
tracygjg profile image
Tracy Gilmore • Edited

Sir, You might find wrapping your source code examples in
'''JavaScript
''' where apostrophise are back-ticks.
For example:

console.log('Hello World!');
Enter fullscreen mode Exit fullscreen mode