Two of the most common ways to access the properties of an object are dot notation and bracket notation.
Each method has its advantages and disadvantages, so let’s see when to use each of them 👇
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 the properties of an object. It uses the object name followed by a dot and then the property name.
object.property
- object: The object that contains 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 is easier to read and understand.
Bracket Notation
Bracket notation allows you to access the properties of an object using a string inside brackets.
object[property]
- object: The object that contains the property.
- “property”: The name of the property in quotes, or an expression that evaluates to a string.
This way is somewhat less convenient, but it is useful in certain cases. For example, when the property name contains invalid characters for dot notation.
Let’s also see it with an example. 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 (which you do not know until runtime)
- Special characters: Allows access to properties with special characters (for example, 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 it.
Let’s see 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]];
It’s actually the same case as the previous one.