Why the new carrot object formed , well I think that vegetable's property name is updating to carrot but it actually creates a new carrot object

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

// Only change code below this line
class Vegetable {
this.name = name;
// Only change code above this line

const carrot = new Vegetable('carrot');
console.log(carrot.name); // Should display 'carrot'
console.log(new Vegetable('carrot'))
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36

Challenge: Use class Syntax to Define a Constructor Function

Link to the challenge:

well you have two objects in your code:

const carrot = new Vegetable('carrot');


new Vegetable('carrot')

so the output will be for sure:

{ name: ‘carrot’ }

the first it’s only carrot because,
you saved the new object inside a variable(carrot) and used it in console.log(carrot.name)
and the second result it gets the output like that because you introduced the:

new Vegetable(…)

inside the console.log() directly,
so if you delete one of them and submit it will work or submit with both, it works too

new, if you put into it before a constructor function call (as here: new Vegetable) creates a new object. So you’re logging an object you’ve just created.

Like, if I do this, this is perfectly valid JS. Useless, but perfectly valid:

new Vegetable("carrot");
new Vegetable("carrot");
new Vegetable("carrot");
new Vegetable("carrot");

I’d have just created 4 objects. They aren’t assigned to any variable, so they’re basically useless, but there will be [for a very short time] 4 objects of type Vegetable that look like { name: "carrot"}

The bit just above that, same thing, except you’ve assigned the object to a variable called carrot, making it actually useful (so you can go carrot.name etc.).

Now I get it, thanks for the help!!

1 Like

thanks to u alsooo :slightly_smiling_face:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.