Có 2 cú pháp truy cập property: Dot notation và Bracket notation.
1. Dot Notation (Ký hiệu chấm)
object.propertyName;
- Property name phải là valid identifier: bắt đầu bằng chữ,
$,_; chỉ chứa chữ, số,$,_. - Không thể dùng biến làm key.
- Ngắn gọn, dễ đọc, được linter khuyến khích.
Ví dụ
<script>
const person = {
firstName: 'Ram',
lastName: 'Kumar',
age: 50,
designation: 'Content Developer'
};
document.write(person.firstName + ' is in a role of ' + person.designation);
// "Ram is in a role of Content Developer"
</script>
2. Bracket Notation (Ký hiệu ngoặc vuông)
object['propertyName'];
object[variableHoldingKey];
- Key là string (có thể chứa space, ký tự đặc biệt, số, unicode).
- Key có thể là biến hoặc biểu thức.
- Bắt buộc cho key không hợp lệ identifier.
Ví dụ
<script>
const person = {
firstName: 'Ram',
lastName: 'Kumar',
'full name': 'Ram Kumar', // Key có space
123: 'numeric key'
};
document.write(person['firstName'] + ' is ' + person['designation']);
// "Ram is Content Developer"
// Key trong biến
const key = 'full name';
document.write(person[key]); // "Ram Kumar"
// Key số
document.write(person[123]); // "numeric key"
// person.123 // SyntaxError!
</script>
So sánh
| Đặc điểm | Dot Notation | Bracket Notation |
|---|---|---|
| Key hợp lệ identifier | ✓ | ✓ |
| Key có space/ky tự đặc biệt | ✗ | ✓ |
| Key là biến/biểu thức | ✗ | ✓ |
| Key là số | ✗ | ✓ |
| Độ đọc code | Cao | Thấp hơn |
| Minification friendly | Có (rename property) | Không (string literal) |
Best Practice
- Mặc định dùng dot notation — dễ đọc, hỗ trợ refactor/rename.
- Dùng bracket notation khi: key dynamic, key invalid identifier, key là số.
- Trong destructuring:
const { 'full name': fullName } = person;(rename).