WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Advanced · question 60 of 100

What are JavaScript decorators, and how do you use them?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

JavaScript decorators are a language feature introduced in ECMAScript 2017 (ES2017) that allow developers to modify the behavior of classes and their members (properties and methods) at runtime. They are functions that wrap around classes and/or their members and can add, modify, or remove functionality.

Decorators are applied using the "@" symbol followed by the name of the decorator function. They are used to annotate classes, methods, or properties and are typically used to implement cross-cutting concerns, such as logging, caching, or validation.

Here’s an example of a decorator that logs the execution of a method:

    function log(target, name, descriptor) {
        const original = descriptor.value;
        descriptor.value = function (...args) {
            console.log(`Calling ${name} with arguments: ${args}`);
            const result = original.apply(this, args);
            console.log(`Returned value: ${result}`);
            return result;
        };
        return descriptor;
    }
    
    class Calculator {
        @log
        add(a, b) {
            return a + b;
        }
    }
    
    const calculator = new Calculator();
    console.log(calculator.add(2, 3)); // Calling add with arguments: 2,3, Returned value: 5

In this example, the log function is a decorator that takes three parameters: target, name, and descriptor. The target parameter refers to the class or object being decorated, the name parameter refers to the name of the method or property being decorated, and the descriptor parameter is an object that contains the definition of the method or property.

Inside the log function, the original method is replaced with a new method that logs the arguments and return value of the original method. The descriptor object is then returned, which represents the modified method.

The @log decorator is then applied to the add method of the Calculator class, which modifies the behavior of the add method by adding logging statements.

JavaScript decorators are a powerful feature that can help to simplify the implementation of cross-cutting concerns in applications. However, they should be used judiciously to avoid making the codebase overly complex and difficult to understand.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics