JavaScript — Dots and Brackets

“This is the story of a girl, who cried a river and drowned the whole world! And while she looks so sad in photographs, I absolutely love her, when she smiles!”

— Absolutely by Nine Days

Just a friendly reminder to smile!

Dots and brackets. They look so totally different, but are they? Not really! Both dots and brackets are used to access properties on JavaScript objects. In many cases, object.property and object[“property”] can be used interchangeably.

Example

var ben= {favoriteFood: “Spinach”, favoriteAnimal: “Owl”}
ben.favoriteFood === ben[“favoriteFood”]; //returns true

You can imagine that the dot magically transforms into the complete bracket syntax ([“ ”]) surrounding your property. It is shorthand bracket notation.

So… if they are the same, why do both exist?

Good question! Dots are easy and straightforward. I like to use them whenever I can! But sometimes, you will be using a variable to access the properties. That doesn’t work out too well with dot notation.

*This next example will use a for…in loop. If your reaction to that was, “A what loop?” here is a synopsis. for…in loops access each property on an object until it has accessed them all.*

Example

//We will use Ben from above.
for(var key in ben){
console.log(ben[key]); //This will work.
console.log(ben.key); //This will not.
}

So, if they are the same, why does one work and not the other?

^^ They aren’t the same! ^^

That is the fundamental difference between the two property-referencing styles. The dot will turn into the full [“ ”], which requires the specific name of the property. In the example, ben has no property named key. But, on the first iteration, key = “favoriteFood”, which totally works when passed into ben[].

In short, dot notation requires the actual property name, bracket notation does not.


I hope this helped! Check back for more JavaScript blogs coming soon!