DEV Community

mmvergara
mmvergara

Posted on

What Does the "new" Keyword do in JavaScript under the hood?

Let’s talk about the new keyword in JavaScript. It’s like the magic wand that makes constructor functions do their thing. But what’s really going on behind the scenes?

  1. Pulls Out a Fresh Object

    The first thing new does is whip up a shiny, empty object. Think of it as a blank canvas waiting to be painted on.

  2. Links It Up

    That blank object? It gets hooked up to the prototype of the constructor function. Now it knows who its “parent” is, like getting added to a cool family tree.

   obj.__proto__ = ConstructorFunction.prototype;
Enter fullscreen mode Exit fullscreen mode
  1. Hands Over the Keys Inside the constructor, this becomes the new object. You can now slap on some properties and methods like you’re decorating your new room.
   ConstructorFunction.call(obj);
Enter fullscreen mode Exit fullscreen mode
  1. Goes With the Flow Finally, it checks if your constructor is returning something specific. If not, it shrugs and hands back the new object it made earlier.

Example time:

function Animal(type) {
  this.type = type;
}

const cat = new Animal('cat');
console.log(cat.type); // cat
Enter fullscreen mode Exit fullscreen mode

Without new, all this cool stuff doesn’t happen—this points to the wrong place, and the prototype chain? Totally busted. So yeah, new is like your friendly helper, making sure everything runs smoothly when you’re building stuff.

Top comments (0)