How to Access Object Properties in JavaScript: Simple Guide
In JavaScript, you can access object properties using
dot notation like object.property or bracket notation like object['property']. Dot notation is simpler but bracket notation is useful when property names have spaces or special characters.Syntax
You can access properties of an object in two main ways:
- Dot notation: Use a dot followed by the property name (e.g.,
object.property). - Bracket notation: Use square brackets with the property name as a string (e.g.,
object['property']).
Bracket notation is helpful when property names are dynamic or not valid identifiers.
javascript
const object = { name: 'Alice', age: 25 }; // Dot notation console.log(object.name); // Bracket notation console.log(object['age']);
Output
Alice
25
Example
This example shows how to access properties using both dot and bracket notation, including a property with a space in its name.
javascript
const person = { firstName: 'John', lastName: 'Doe', 'favorite color': 'blue' }; // Access with dot notation console.log(person.firstName); // John // Access with bracket notation console.log(person['lastName']); // Doe // Access property with space using bracket notation console.log(person['favorite color']); // blue
Output
John
Doe
blue
Common Pitfalls
Some common mistakes when accessing object properties include:
- Using dot notation for property names with spaces or special characters (this causes errors).
- Forgetting quotes around property names in bracket notation.
- Trying to access properties that do not exist, which returns
undefined.
javascript
const obj = { 'my prop': 10 }; // Wrong: dot notation with space in property name // console.log(obj.my prop); // SyntaxError // Right: bracket notation with quotes console.log(obj['my prop']); // 10 // Accessing non-existing property console.log(obj.age); // undefined
Output
10
undefined
Quick Reference
| Access Method | Usage | When to Use |
|---|---|---|
| Dot notation | object.property | Simple, valid identifier property names |
| Bracket notation | object['property'] | Property names with spaces, special characters, or dynamic keys |
Key Takeaways
Use dot notation for simple, valid property names.
Use bracket notation when property names have spaces or special characters.
Always put quotes around property names in bracket notation.
Accessing a missing property returns undefined, not an error.
Bracket notation allows dynamic property access using variables.