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

Denise Edwards
Denise Edwards
4,924 Points

So how do you do this then?

So the second part of the challenge in Access and Set Object Properties portion of the Loops, Arrays and Objects bit in the Javascript Track, says this:

Challenge Task 2 of 2

Add a new property -- country -- to newYork. Don't change the original object, just add this new property using a = sign to assign the country property to USA.

Here was the existing code:

var newYork = {
  population: 100, 
  latitude: '40.7127 N',
  longitude: '74.0059 W'
  country: 'USA' //I added this bit here, which is actually incorrect
};

population = 8.406e6; //This was from the 1st task

I eventually got past the challenge by just changing the original object literal, but as that was actually the opposite of what the challenge asked, how exactly do you add a property to an existing object?

I tried both

newYork['country'] = 'USA';

and

newYork.country = 'USA';

but neither seemed to work... :/

2 Answers

Hey Denise,

Both

newYork['country'] = 'USA';

and

newYork.country = 'USA';

will let you add properties to the newYork object. For this challenge, the code should look something like this:

var newYork = {
  population: 100, 
  latitude: '40.7127 N',
  longitude: '74.0059 W'
};

newYork.population = 8.406e6; // First Task: change value of existing property
newYork.country = 'USA'; // Second Task: add new property to object

Alternatively you can also use this:

var newYork = {
  population: 100, 
  latitude: '40.7127 N',
  longitude: '74.0059 W'
};

newYork['population'] = 8.406e6; // First Task: change value of existing property
newYork['country'] = 'USA'; // Second Task: add new property to object
Denise Edwards
Denise Edwards
4,924 Points

Hmm, I guess it must have been a glitch why it didn't work. Well, at least I know I wasn't missing anything. Thanks, Huy!