Dot Notation vs Bracket Notation for Object Properties – What's the Difference?
Fahad Bin Faiz
Posted on November 12, 2024
Dot Notation
Dot notation is simpler and more readable. It's used when:
- The property name is a valid identifier (contains only letters, digits, $, or _, and doesn’t start with a digit).
- You know the property name ahead of time.
For example:
const person = { name: 'alice', age: 30 };
console.log(person.name); // 'alice'
Bracket Notation
Bracket notation is more flexible and allows you to:
- Use property names stored in variables.
- Access properties with special characters, spaces, or numbers that aren’t valid identifiers.
- Dynamically build property names at runtime.
Examples:
1. Using variables to access properties:
const person = { name: 'alice', age: 30 };
const prop = 'name';
console.log(person[prop]); // 'alice'
2.Properties with special characters or spaces:
const person = { 'first name': 'alice', age: 30 };
console.log(person['first name']); // 'alice'
3.Dynamically generated property names:
const property = 'name';
console.log(person[property]); // 'alice'
When to Use Bracket Notation
- If the property name is dynamic or stored in a variable.
- If the property name has spaces, special characters, or starts with a number.
For most other cases, dot notation is preferred because it’s more readable and concise.
💖 💪 🙅 🚩
Fahad Bin Faiz
Posted on November 12, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
dotnotation Dot Notation vs Bracket Notation for Object Properties – What's the Difference?
November 12, 2024
dotnotation Dot Notation vs Bracket Notation for Object Properties – What's the Difference?
November 16, 2024