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 Object-Oriented JavaScript (2015) Introduction to Methods Modifying Objects with Methods

Ginger Williams
Ginger Williams
6,409 Points

How does it know to store the values?

How does it know to store the values?... is there a cache system?

samiff
samiff
31,206 Points

Not 100% sure if I'm clear on what you're asking, but the calculator object has a 'sum' variable which is used to retain the data. Did you mean something else?

Ginger Williams
Ginger Williams
6,409 Points

yes but why does the browser retain the last sum after the function is run to add it to the number once the function is run again ?

samiff
samiff
31,206 Points

Yes, the browser is holding the calculator object in memory on that page. As longs as the object exists in memory, the 'sum' property for that object will exist as well (and any modifications made to it or the object itself). If you refresh or navigate away from the page however, the browser basically says 'I don't need to remember this object anymore' so you wouldn't be able to refresh and expect to retrieve a sum you had previously stored.

Jordan Gauthier
Jordan Gauthier
5,552 Points

When you declare a variable like lastSum, your computer allocates space in memory (RAM) to hold whatever value is stored in the variable. Behind the scenes, your computer uses that memory's address location to read or write the value.

Of course, once the variable leaves scope, the allocated memory is freed back up for another program to use if needed.

Ginger Williams
Ginger Williams
6,409 Points

Thank you I did't know that. I thought that is something I would have to add to the function.

1 Answer

Chetan Jaisinghani
Chetan Jaisinghani
2,896 Points

Not quite sure if this is what you're asking:

In simpler words, every time we fire the function that adds the number we provide, the number (value) is added to "this.sum".

calculator.add(6) (this.sum becomes 0 (initial value) + 6, so now this.sum equals to 6) calculator.add(4) (this.sum becomes 10, i.e. 6 from the previous firing of the function and then adding 4 to it) calculator.add(10) (this.sum now becomes 20)