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

General question about Objects

This is not part of any Treehouse course (it's from the "You Don't Know JS" book series), but I'd really appreciate your help:

In the following code:

var obj = {
    a: "hello world",
    b: 42
};

var b = "a";

obj[b];         // "hello world"
obj["b"];       // 42

... how come obj[b] returns "hello world" ? I really don't understand it....

Thanks in advance.

2 Answers

Steven Parker
Steven Parker
243,253 Points

Since b is a string variable that contains the letter "a", the expression obj[b] is the same thing as obj["a"] which is also the same thing as obj.a.

All of them access the "a" property of obj, which contains "hello world".

This is a good illustration of how variable name choice can influence how easy a program is to understand and maintain. For example, it might have been much less confusing if the variable b had been given the name prop instead.

Thanks a lot for this, Steven. Now it's clearer. But... isn't this a glitch or bug, technically?

Steven Parker
Steven Parker
243,253 Points

No, it's certainly not a bug. The variable names and property names in this example may have been chosen specifically to test your powers of observation.

But I wouldn't call this a "best practice". In good code, names should be chosen for clarity.