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 Loops, Arrays and Objects Tracking Data Using Objects Accessing Object Properties

13,797 Points

I'm confused, we changed the value for (person.name), and when we print we see both values. Why? I come from Java OOP.

I learned OOP in Java. When I create an object called person. Instantiate the object with the name variable value of "Sarah". Then change it to "Rainbow Dash". Finally displaying the same sentence as in this example but in Java, I get ...

-- Hello, My Name is Rainbow Dash -- I live in the US -- But, I wish my name was Rainbow Dash

Sense I call the print function(method) at the end, just like this example, in Java, the name variable(parameter) becomes "Rainbow Dash". So why in JavaScript does it not change the first instance, when it printing after the name has changed?

Steven Parker
Steven Parker
229,018 Points

What do you get in JavaScript? And can you share the actual code?

I'd guess this was scope-related, but no way to tell without seeing the code.

13,797 Points

Talked with a buddy, and figured out where my misunderstanding was. Thanks.

2 Answers

JavaScript object values can only be modified, if called by the object.property name and assigning a new value after the declaration

like this

var person = {
  name : 'Sarah',
  country : 'US',
  age : 35,
  treehouseStudent : false,
  skills : ['JavaScript', 'HTML', 'CSS']

person.name= 'John';

Now this prints out Hello my name is John.I live in US

But with Angular.js you can change the object property value quite easily.

So it doesn't change the original name of Sarah, because object.property only changes the value after the declaration. Is there another method that does change the original property value as well?

Well since your declaring a variable you can simply just make it dynamic by prompting the User for their name or using a textbox to get the name and creating a new object property with the name.

person[name] = prompt("Whats your name? ");

return value is always a string