Explain the difference between dot notation and bracket notation for accessing object properties
TL;DR
Dot notation and bracket notation are two ways to access properties of an object in JavaScript. Dot notation is more concise and readable but can only be used with valid JavaScript identifiers. Bracket notation is more flexible and can be used with property names that are not valid identifiers, such as those containing spaces or special characters.
const obj = { name: 'Alice', 'favorite color': 'blue' };
// Dot notation
console.log(obj.name); // Alice
// Bracket notation
console.log(obj['favorite color']); // blue
Dot notation vs. bracket notation
Dot notation
Dot notation is the most common and straightforward way to access object properties. It is concise and easy to read but has some limitations.
Syntax
object.property;
Example
const person = {
name: 'Alice',
age: 30,
};
console.log(person.name); // Alice
console.log(person.age); // 30
Limitations
- Property names must be valid JavaScript identifiers (e.g., no spaces, special characters, or starting with a number)
- Property names cannot be dynamic (i.e., they must be hardcoded)
Bracket notation
Bracket notation is more flexible and can be used in situations where dot notation cannot.
Syntax
object['property'];
Example
const person = {
name: 'Alice',
'favorite color': 'blue',
1: 'one',
};
console.log(person['name']); // Alice
console.log(person['favorite color']); // blue
console.log(person[1]); // one
Advantages
- Can access properties with names that are not valid JavaScript identifiers
- Can use variables or expressions to dynamically determine the property name
Example with dynamic property names
const property = 'name';
console.log(person[property]); // Alice