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

Dot vs Bracket Notation

Why does Dave use dot notation when mixing objects/arrays, but when he was explaining For In loops, he specifically said to use bracket notation or else the function will be looking for a property/key with the exact name used in the dot notation.

Can somebody please explain the difference?

Thanks!

1 Answer

andren
andren
28,558 Points

Well the difference is pretty much exacly what you noted in your question. When you use dot notation JavaScript will look for properties whose name match the word you provide exactly.

With bracket notation JavaScript will interpret your input as code, meaning that if you reference a variable name for instance then JavaScript will look for properties matching the value of that variable, not the name of the variable itself.

Here is an example:

var exampleString = "message"

var exampleObject = {
    message: "Hello World"
}

console.log(exampleObject[exampleString])
// JavaScript will look for a property called "message"
// since that is what the "exampleString" holds.

console.log(exampleObject.exampleString)
// JavaScript will look for a property called "exampleString"
// since that is the exact word you provided.

As you can probably guess the first of those console.log statements ends up printing out "Hello World". While the second ends up printing undefined, since exampleString is not a property that exist in the exampleObject.