Access properties in javascript
JavaScript Fundamentals
How to Access JavaScript Object Properties (Dot vs Bracket)
JavaScript offers two primary syntaxes for reading and writing object properties: dot notation and bracket notation. Mastering both patterns ensures your code works with dynamic keys, external data, and reserved words.
Dot Notation
Concise, autocomplete friendly, works with valid identifiers (letters, digits, underscores).
Bracket Notation
Handles dynamic property names, strings with spaces, numbers, and characters disallowed in identifiers.
Dot Notation
const book = {
id: 2,
title: "JavaScript Essentials",
author: "Coder Website"
};
console.log(book.id); // 2
console.log(book.title); // "JavaScript Essentials"
Remember: Property names must be valid identifiers (no spaces or hyphens) to use dot notation.
Bracket Notation
Bracket notation accepts any string or expression inside the brackets. Use it for keys with spaces, numbers, or when using variables.
const dynamicKey = "title";
console.log(book[dynamicKey]); // "JavaScript Essentials"
console.log(book["author"]); // "Coder Website"
When You Must Use Bracket Notation
Keys with Spaces or Hyphens
const movie = {
"release date": "2024-08-01"
};
console.log(movie["release date"]); // works
console.log(movie.release date); // SyntaxError
Numeric Property Names
const stats = {
1: "Bronze",
2: "Silver",
3: "Gold"
};
console.log(stats[1]); // "Bronze"
console.log(stats.1); // SyntaxError
Working with Dynamic Keys
External data (e.g., API responses) often requires dynamic property access.
const response = {
metrics: {
visits_2024: 12000,
visits_2023: 9800
}
};
function getMetric(year) {
const key = `visits_${year}`;
return response.metrics[key] ?? 0;
}
console.log(getMetric(2024)); // 12000
Dot vs Bracket at a Glance
| Scenario | Preferred Syntax | Reason |
|---|---|---|
| Static, known keys | Dot notation | Cleaner syntax, IDE autocomplete support |
| Keys with spaces or symbols | Bracket notation | Dot notation is invalid syntax |
| Access via variables | Bracket notation | Allows expression evaluation inside brackets |
| Numeric keys | Bracket notation | Dot notation treats numbers as invalid identifiers |