Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Objects Object Basics Set the Value of Object Properties

person.nickname creation outside of {}

Instead of creating person.nickname outside of the object " {} "

isn't it a better practice to add it inside an existing " {} " than outside?

Trent Stenoien
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Trent Stenoien
Full Stack JavaScript Techdegree Graduate 20,034 Points

Both of these are functionally the same. Throw these into the console and log each object to see how they're stored.

const person1 = {}; person1.nickname = 'Trent';

const person2 = { nickname: 'Trent' };

1 Answer

Steven Parker
Steven Parker
220,683 Points

If the value is known at creation time, it would certainly make sense to include it in the object literal. But I think the point of the lesson is to show that you can add new properties to an existing object. In a more complicated situation, it might be necessary to construct an object at one time, but add one or more properties to it at a later time.

Thank you Steven. It's nice to know there are other options and can even place it outside the " {} "

But I've got another question. Instead of it being placed outside the " {} " and create the " person.nickname = "Duke " "

Why don't they just go back putting this inside the {} so it doesn't get scattered everywhere? Is this generally what real projects are done or they leave it outside the " {} " when adding sometimes.

Steven Parker
Steven Parker
220,683 Points

As I said, in a real project to choice to include a property in an object literal will mostly depend on if it is already known. If it is something that will be calculated or input by the user, it will be necessary to add it to the object later.