Problem Statement
What are the two ways to access object properties?
Explanation
JavaScript provides two ways to access object properties.
Dot notation is cleaner and more common. Use it when property names are valid identifiers.
Bracket notation is more flexible. Use it when property names have spaces, start with numbers, are stored in variables, or are computed dynamically.
Both work the same way but bracket notation is more powerful.
For setting properties, both notations work identically.
Code Solution
SolutionRead Only
const person = {
name: 'John',
age: 30,
'favorite color': 'blue'
};
// Dot notation (most common)
console.log(person.name); // 'John'
person.age = 31;
// Bracket notation (more flexible)
console.log(person['name']); // 'John'
person['age'] = 32;
// When bracket notation is needed
// Property with spaces
console.log(person['favorite color']); // 'blue'
// person.favorite color // Syntax error!
// Property in variable
const prop = 'name';
console.log(person[prop]); // 'John'
// Computed property names
const key = 'age';
console.log(person[key]); // 32
// Dynamic access
function getValue(obj, property) {
return obj[property];
}
console.log(getValue(person, 'name')); // 'John'
// Property starting with number
const data = {'1st': 'first'};
console.log(data['1st']); // 'first'
// console.log(data.1st); // Syntax error!