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 JavaScript Loops, Arrays and Objects Tracking Data Using Objects Mixing and Matching Arrays and Objects

Robert Mews
Robert Mews
11,540 Points

Dot notation vs. bracket?

I noticed that when we want to retrieve a value of an object property, we use the dot notation (i.e. object.prop name). However, if we want to retrieve that same object property using a for in loop, we use backers (i.e. object[prop name]). I find this somewhat confusing and am trying to understand why the difference?

2 Answers

Dave explains this in 'Using for in to Loop Through an Object's Properties' around the 1:45 mark. Here's the transcript:

In fact, the only way to access an object property using the for-in loop, is with a bracket notation, you can't use dot notation. For example, this [SOUND] wont work. Why? Because this would look for a property that is literally named propName. The JavaScript interpreter can't substitute the value of that variable, the property's name, when using dot notation. Just keep that in mind, only bracket notation will work when using the for-in loop.

Justin Black
Justin Black
24,793 Points

Square bracket notation allows use of characters that can't be used with dot notation as per: http://www.dev-archive.net/articles/js-dot-notation/

var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax

The second advantage of square bracket notation is when dealing with variable property names.

for (var i = 0; i < 10; i++) {
  someFunction(myForm["myControlNumber" + i]);
}

Roundup:

Dot notation is faster to write and clearer to read. Square bracket notation allows access to properties containing special characters and selection of properties using variables

For more up to date information you can check this:

http://stackoverflow.com/questions/17189642/difference-between-using-bracket-and-dot-notation