Explorer
JavaScript

Write a function `myNew(Constructor, ...args)` that mimics the behavior of the `new` keyword.

Problem Statement

<p>Write a function <code>myNew(Constructor, ...args)</code> that mimics the behavior of the <code>new</code> keyword.</p>

Examples

Input: myNew(Person, "Alice", 30)

Output: New instance with Person.prototype and initialized properties

Explanation: Simulates the `new` operator instantiation mechanism.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: new does 4 things: creates object, sets prototype, calls constructor, returns result. šŸ’” Hint 2: Create an object with Object.create(Constructor.prototype). šŸ’” Hint 3: Call the constructor with the new object as `this`. If it returns an object, use that; otherwise return the created object.

Editorial & Approach

Problem Overview & Intuition

To solve Implement new Operator, we consider the execution characteristics of JavaScript engines. Write a function `myNew(Constructor, ...args)` that mimics the behavior of the `new` keyword. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (new does 4 things: creates object, sets prototype, calls constructor, returns result).
  3. Implement Logic: Handle state and transformations efficiently (create an object with object.create(constructor.prototype)).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function myNew(Constructor, ...args) {
  const obj = Object.create(Constructor.prototype);
  const result = Constructor.apply(obj, args);
  return typeof result === "object" && result !== null ? result : obj;
}

Complexity Analysis

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Implement new Operator

Hard

Write a function myNew(Constructor, ...args) that mimics the behavior of the new keyword.

Example Scenarios
1Example 1
Input: myNew(Person, "Alice", 30)
Output: New instance with Person.prototype and initialized properties
Explanation:

Simulates the `new` operator instantiation mechanism.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
["Alice",30,"Hi, Alice",true]