For these examples, let’s use the object literal from yesterday’s post:
Usually, we access an object’s properties and methods using dot notation.
For the object above, that would look like this:
It’s possible to do this with bracket notation, too:
Why two options?
Bracket notation is necessary when you need to get a property/method name programmatically.
This could be because it’s saved to a variable, the result of a function call, or any number of reasons.
For a simple use case, imagine I have a variable called
dogSpeak, and its value is the string
I can’t just do the following, because there isn’t a
dogSpeak() method. I’ll get a
We have to use bracket notation here. Notice that I’m not using quotes, because
dogSpeak is the name of a variable:
This works because the value of the
dogSpeak variable is the string
"bark", so it invokes the
- We use dot notation most of the time.
- We use bracket notation when we need to get a property/method name programmatically.
For more information, check out property accessors in the MDN Web Docs. 👍
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!