Hiprup

What is the new keyword and what does it do?

The new keyword creates an instance from a constructor function or class. Behind the scenes it does four things:

  1. Creates a fresh empty object.

  2. Links it to the constructor's prototype.

  3. Runs the constructor with this bound to the new object.

  4. Returns that object automatically (unless the constructor returns its own object).

Gotcha: forgetting new can leak properties onto the global object, or throw in strict mode.

// Constructor function
function Person(name, age) {
  // 'this' is the new empty object (step 3)
  this.name = name;
  this.age = age;
}
Person.prototype.greet = function() {
  return `Hi, I'm ${this.name}`;
};

const john = new Person('John', 30);
console.log(john.greet());               // "Hi, I'm John"
console.log(john instanceof Person);      // true
console.log(john.__proto__ === Person.prototype); // true (step 2)

// What 'new' does internally (simplified)
function myNew(Constructor, ...args) {
  const obj = Object.create(Constructor.prototype); // Steps 1-2
  const result = Constructor.apply(obj, args);       // Step 3
  return result instanceof Object ? result : obj;    // Step 4
}

const jane = myNew(Person, 'Jane', 25);
console.log(jane.greet()); // "Hi, I'm Jane"

// Without new — bug!
// const broken = Person('Bob', 20); // this = global/undefined!
// console.log(broken); // undefined (no return statement)

new creates an empty object, links its prototype, calls the constructor with this as the new object, and returns it. The myNew implementation shows the four steps explicitly.

Without new, this points to global (sloppy mode) or is undefined (strict mode), causing name/age to become global variables or throwing TypeError.

Know the four steps of new. The myNew implementation is a classic interview coding question.

The 'without new' bug (this = global) explains why classes enforce new. Show instanceof and prototype chain verification.

What is the new keyword and what does it do? | Hiprup