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 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
216,810 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