Two of the most common ways to access an object’s properties are dot notation and bracket notation.
Each method has its advantages and disadvantages, so let’s see when to use each one 👇
| Feature | Dot Notation | Bracket Notation |
|---|---|---|
| Access to properties | Yes | Yes |
| Use of variables | No | Yes |
| Property names | Limited | Any |
| Readability | More readable | Less readable |
Dot Notation
Dot notation is the most common way to access an object’s properties. You use the object’s name followed by a dot and then the property name.
object.property
- object: The object containing the property.
- property: The name of the property you want to access.
For example,
const student = {
name: "Luis",
age: 30
};
To access the name property:
student.name; // "Luis"
Advantages of Dot Notation
- Clarity: It’s easier to read and understand.
Bracket Notation
Bracket notation allows you to access an object’s properties using a string inside brackets.
object[property]
- object: The object containing the property.
- “property”: The property name in quotes, or an expression that evaluates to a string.
This form is a bit less convenient, but it’s useful in certain cases. For example, when the property name contains characters that are invalid for dot notation.
Let’s see it with an example as well. To access the name property using bracket notation we would do:
student["name"]; // "Luis"
Advantages of Bracket Notation
- Dynamic Names: Allows access to properties with dynamic names (that you don’t know until runtime).
- Special Characters: Allows access to properties with special characters (e.g., spaces).
When to Use Bracket Notation
In general, we will primarily use dot notation. We will use brackets when we have a case where we cannot use dot notation.
Let’s look at them.
Properties with Special Characters
Bracket notation is necessary if the property name contains special characters or spaces.
const person = {
"full name": "Ana Pérez"
};
person["full name"]; // "Ana Pérez"
person.full name; // ❌ I can't do that because of the space
Dynamic Properties
When the property name is determined at runtime.
const property = "age";
person[property]; // 21
person.¿?¿?¿? // ❌ We wouldn't know what to put there
Computed Properties You can use expressions inside the brackets to access properties that are generated dynamically.
const index = 2; // imagine the user selects this
const properties = ["name", "age", "profession"];
person[properties[index]];
This is actually the same case as the previous one.
