JS dot-notation vs. bracket notation

. 
[]
var cat = { 
property1: "meow",
property2: "hiss"
}
cat.property1
cat.property1
"meow"
cat["property1"]
"meow"
var x = "property2"
cat.property2
cat.property2
"hiss"
cat.x
undefined
cat[x]
hiss
cat[x]
hiss
cat["property2"]
hiss
cat.x
cat
Object {property1: "meow", property2: "hiss"}
var dog = {attribute1: "loving", attribute2: "trueBlue"}
cat["loving"] = "something cat's are not"
cat.dog.attribute1
TypeError: Cannot read property 'attribute1' of undefined
cat[dog["attribute1"]]
"something cat's are not"
cat["loving"]
"something cat's are not"
var y = dog
var z = "attribute1"
cat[y[z]]
"something cat's are not"
  • In a JS object, all property keys are strings.
  • Dot notation only lets you access the explicit key name of a property.
  • You can’t use dot notation with variables (or numbers either).
  • JS evaluates the first complete expression with square brackets in a statement, runs toString() on it to convert it into a string and then uses that value for the next bracket expression, on down the line till it runs out of bracket expressions.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
code_thoughts

code_thoughts

More from Medium

Implementing infinispan cache hotrod client in Java

CS373 Spring 2022: David Trakhtengerts

Divide & Conquer VS Dynamic Programming

What Is Koa Js ?