In JavaScript, there are two main ways to access an object's properties and methods. These are dot notation and bracket notation. They're both a type of property accessor.
For these examples, let's use the object literal from yesterday's post:
var dog = {
name: "Yoko",
breed: "Labrador",
bark: function () {
return "Woof!";
}
};
Dot notation
Usually, we access an object's properties and methods using dot notation.
For the object above, that would look like this:
dog.name; // Yoko
dog.breed; // Labrador
dog.bark(); // Woof!
Bracket notation
It's possible to do this with bracket notation, too:
dog["name"]; // Yoko
dog["breed"]; // Labrador
dog["bark"](); // Woof!
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 "bark"
:
var dogSpeak = "bark";
I can't just do the following, because there isn't a dogSpeak()
method. I'll get a TypeError
:
dog.dogSpeak(); // TypeError: dog.dogSpeak is not a function
We have to use bracket notation here. Notice that I'm not using quotes, because dogSpeak
is the name of a variable:
dog[dogSpeak](); // Woof!
This works because the value of the dogSpeak
variable is the string "bark"
, so it invokes the bark()
method.
Summary
There are two main types of property accessor in JavaScript.
- 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. 👍