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 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 21,632 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
231,110 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
231,110 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.