DEV Community

mmvergara
mmvergara

Posted on

2 1 1 1 1

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay