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 59 of 100

How do you implement a custom "new" operator in JavaScript to create objects?

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

The "new" operator in JavaScript is used to create an instance of a constructor function. When you call a constructor function with the "new" keyword, a new object is created, and the constructor function is called with the "this" keyword referring to the new object. The constructor function then initializes the new object with properties and methods.

To implement a custom "new" operator, you need to create a function that performs the same steps as the built-in "new" operator. Here is an example of how to do this:

    function CustomNew(constructor, ...args) {
        // Create a new object with the prototype of the constructor function
        const obj = Object.create(constructor.prototype);
        // Call the constructor function with the new object as "this" and the arguments
        const result = constructor.apply(obj, args);
        // Return the new object if the constructor function doesn't return an object
        return typeof result === 'object' ? result : obj;
    }

This function takes a constructor function and any arguments that should be passed to it, and returns a new object created with the constructor function.

Here’s an example of how you could use this custom "new" operator:

    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    
    const person1 = CustomNew(Person, 'John', 30);
    console.log(person1); // {name: "John", age: 30}
    
    const person2 = new Person('Jane', 25);
    console.log(person2); // {name: "Jane", age: 25}

In this example, we create a constructor function called "Person" that takes two parameters, "name" and "age". We use the custom "new" operator to create a new instance of the "Person" constructor function and pass it the parameters "John" and 30. We also create a new instance of the "Person" constructor function using the built-in "new" operator and pass it the parameters "Jane" and 25. Finally, we log both objects to the console to verify that they were created correctly.

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