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 Introduction to Programming Objects and Arrays Objects

Jennifer Hruska
Jennifer Hruska
539 Points

variables inside Objects question

Howdy all. I'm just getting started with Objects and was trying to see if I could assign a variable as an object value. It appears to work, however in my example below, it doesn't appear to update after changing it. Is there some other way I have to get that value to update? Thanks!

//

var vstGUI = true;

var VIPdatabases = {

pluginName : "Absynth",
pluginID : 1,
pluginVrs : 2.1,
"VST3" : vstGUI

}

vstGUI = false;

console.log(VIPdatabases["pluginName"]);

console.log(VIPdatabases["pluginID"]);

console.log(VIPdatabases["pluginVrs"]);

console.log(VIPdatabases["VST3"]);

//

3 Answers

It's because you set the "VST3" when vstGUI was set to true. Javascript doesn't keep a track of when a variable is changed so if your variable changes you have to tell javascript to update. (fiddle showing same code with an update function http://jsfiddle.net/8E9wM/)

Sean T. Unwin
Sean T. Unwin
28,690 Points

You're sort of on the right track.

Properties of objects are their own variables so you may not need the global vstGUI variable as it may be redundant. When defining properties of an object you want to set their default value, if there is one.

In your example if VIPdatabases.VST3 will default to true (I am assuming since you set vstGUI = true; at the beginning) then when instantiating VIPdatabases you can define VST3: true. Doing this will also establish a variable type, in this case a boolean. Then you can change VIPdatabases.VST3 directly instead of using, what I will call, a mediator variable or middle-man, if you will.

Otherwise, you will be updating both variables anytime the value changes. If you need this to happen that's fine but you may want to create a function that updates both for you so then you can type one line of code instead of two when updating the state change (true/false).

Jennifer Hruska
Jennifer Hruska
539 Points

Great answers. Thanks so much!