Came across new operator help me understand

can someone explain the new operator, dumb it down. I read the MDN DOCs and have a vague understanding but not really sure.

All i know is that it creates a new blank object
and that it links to the constructor for the class syntax .
But like how does it work what does it do?

Can you show us some code and/or the link to the MDN documentation?

Edit: Ahhh… You are talking about the keyword new. I just though you were talking about some ‘new’ operator you didn’t understand.

1 Like

If you want to create a new instance of a thing you have defined, you can use the new keyword.

var myDog = new Dog('Bandit');
myDog.printName(); // "This dog is named Bandit"

var otherDog = new Dog('Ghost');
1 Like

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

how does it link with constructor thats what i’m not sure about

here is the code

// Only change code below this line

class Vegetable{

  constructor(name){

    this.name = name;

  }

}

// Only change code above this line

const carrot = new Vegetable('carrot');

console.log(carrot.name); // Should display 'carrot'

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Oh thanks i didn’t know that, very helpful

This constructor is called here

So the constructor is called when you create the new object and the code inside the constructor function sets up the new object.

then we make another object with new?
and since its also name Vegetable it will be link to that class? with carrot being passed into the constructor param?
Also this is my first time coming across the ‘this’ keyword, with no explaination whatsoever so confused hahaha

Yeah I was confused too when I first learned this :smile:
Mosh’s video explanation helped me

In the context of the constructor this is referring to the object you are creating:

function Poly (name) {
    this.name = name;
    this.check = this;
}

let square = new Poly('square');

console.log(square) //Poly {name: "square", check: Poly};

console.log(square.check) //Poly {name: "square", check: Poly};