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

Tyson Voigtlander
Tyson Voigtlander
2,182 Points

The variable Key being added to the object

I am curious how the variable key with the value "first_name" is being added to the the object me. Shouldn't the value published just be first_name and not jim?

2 Answers

Samuel Webb
Samuel Webb
25,370 Points

It's basically the exact same thing as a normal variable, except that it's within an object and assigned to that object. I'll give you some examples that hopefully explain it a little bit.

var first_name = "Sam"; /* This creates a variable called first_name, with a value of "Sam" */

console.log(first_name); /* This logs the value of first_name to the console. "Sam" is what would be shown */


/* It's the same concept with objects */


var me = { /* This starts the creation of an object named me */

    first_name: "Sam" /* This creates a property(a.k.a. variable) called first_name with the value of "Sam". It just looks a little different. */

} /* This ends the creation of the object */

console.log(me.first_name); /* This logs to the console the value of the first_name property which belongs to the me object */

Not sure if this will help you but hopefully you get it.

Hi Tyson, hi Sam,

I wonder a similar thing: so the property first_name defined in the object is a string, right? I don't mean that the value of this property is a string, but the property itself is represented with a string, have I got this one right?

And the var key Tyson asked about is basically a variable, given a string value, which happens to be that same property string of first_name, right? So, console.log(me[key]) prints the same as console.log(me["first_name"]) and as console.log(me.first_name). I believe I got this last part right, but I'm not really sure about the previous definition part.

Sorry about the chaotic sentences :)

I hope that you'd give feedback so that everyone with the same question marks can see it :)

Cheers!