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 trialPeter Huang
5,427 Pointsperson.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?
1 Answer
Steven Parker
231,261 PointsIf 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.
Peter Huang
5,427 PointsThank 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
231,261 PointsAs 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.
Trent Stenoien
Full Stack JavaScript Techdegree Graduate 21,632 PointsTrent Stenoien
Full Stack JavaScript Techdegree Graduate 21,632 PointsBoth 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' };