Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Ajas Sharafudeen
Ajas Sharafudeen
6,726 Points

Using "new" before Pet class while assigning all the values to a const variable.

I noticed that 'new' is used before Pet class. Is it necessary? Or can we just mention the class name and add details!

const ernie = new Pet('dog', 1, 'pug');
const vera = new Pet('dog', 8, 'border collie');

3 Answers

Emmanuel C
Emmanuel C
10,636 Points

Hey Ajas,

Yes, the "new" keyword is what tells the computer to create a new object that will automatically call its constructor. I come from the backend, from the days of C++. And what the "new" keyword actually did behind the scenes, was tell the computer to set aside some memory from your computers RAM, called the Heap. That memory is then free to be used by your program to store the contents of that object. Almost all Object Oriented Programming languages have the "new" keyword. And its based on that concept.

Tim Knight
Tim Knight
28,888 Points

Hi Ajas,

Yes it's completely correct to add the new keyword before the class. You're essentially creating a new instance of that class and assigning it to the variable. Removing the new keyword would cause an error in the JavaScript file and likely stop it from processing.

Ajas Sharafudeen
Ajas Sharafudeen
6,726 Points

Thank you, Tim Knight and Emmanuel C. I keep on making the mistake of not adding 'new' in the practice session. Your answers will help me remember whenever such a situation happens in the future.