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

Alex Tasioulis
Alex Tasioulis
4,950 Points

key vs property

So, in video 4 of this programing / js intro Jim Hoskins used two different "things" within an object

like first_name vs "Employee Number"

And he explained that "Employee Number" is much better since you can assign it to a variable and then change it and have it be dynamic etc etc.

So why would you use the first version like .first_name ? just because its a bit simpler to type? or are there other upsides?

1 Answer

It's a matter of convenience. The dot notation (myObj.something) is easier to type and cleaner to read. On the other hand, the bracket/subscript notation (myObj["something"]) offers the dynamic aspect at the cost of convenience and readability of your code in general.

But there's something else here in question. JavaScript has something that's called reserved words. They are identifiers that are used as part of the language, and they cannot be used as variable names. If you use the dot notation, you cannot use reserved words as keys, which is a good thing, you don't want to make your code look confusing. But if you use bracket notation, you'll be able to do just that, which leads to some weird-looking code. (Note that all of this depends on the implementation of JS itself. Every browser has its own implementation so some things work a bit differently across various browsers. In fact, the current standard of JavaScript, ES5, allows you to use reserved words as key names, but that doesn't mean it's good practice to do so.)

For instance, var is a reserved word and you want to avoid using it as a variable/property name. The dot notation forces you to avoid using it.

Finally, tools for checking code quality like JSLint and JSHint (something that you'll probably end up using as you get further into JS development) prefer the dot notation. Most of the well-regarded JS development books also recommend the dot notation.

Alex Tasioulis
Alex Tasioulis
4,950 Points

Thank you so much, Dino. You're a treasure trove of information.