Bracket notation offers more flexibility than dot notation. It is required when the property key is not a valid JavaScript identifier (e.g., contains spaces or special characters) or when the property name is stored in a variable.
Example 1: Accessing a Property with a String Key
// Define a user object
const user = {
"first name": "John",
"last name": "Doe"
};
// Access the 'first name' property using bracket notation
console.log(user["first name"]); // Output: John
Explanation: Since the property key "first name"
contains a space, it's not a valid identifier. Therefore, we must use bracket notation with the key as a string.
Example 2: Using a Variable to Access a Property
// Define a product object and a variable for the property name
const product = {
name: "Laptop",
price: 1200
};
let propertyToAccess = "price";
// Access the 'price' property using the variable
console.log(product[propertyToAccess]); // Output: 1200
Explanation: Bracket notation allows for dynamic property access. The variable propertyToAccess
holds the name of the property we want to retrieve.
Example 3: Modifying a Property with a Hyphenated Key
// Define a configuration object with a hyphenated key
const config = {
"api-key": "xyz-123"
};
// Modify the 'api-key' property
config["api-key"] = "abc-456";
console.log(config["api-key"]); // Output: abc-456
Explanation: Property keys with hyphens are not valid identifiers and require bracket notation for both access and modification.
Example 4: Adding a Property with a Key from a Variable
// Define a book object and a variable for the new property key
const book = {
title: "1984"
};
let newProperty = "author";
// Add a new property using the variable as the key
book[newProperty] = "George Orwell";
console.log(book.author); // Output: George Orwell
Explanation: We can dynamically add new properties to an object. The key for the new property is determined by the value of the newProperty
variable.
Example 5: Accessing an Array Element within an Object
// Define a user object with an array of hobbies
const user = {
name: "Alice",
hobbies: ["reading", "hiking", "coding"]
};
// Access the second element of the 'hobbies' array
console.log(user.hobbies[1]); // Output: hiking
Explanation: While we use dot notation to access the hobbies
array itself, we then use standard array bracket notation to access a specific element by its index.
Example 6: Iterating Through Object Properties
// Define a car object
const car = {
make: "Honda",
model: "Civic",
year: 2023
};
// Loop through the properties of the car object
for (const key in car) {
console.log(`${key}: ${car[key]}`);
}
// Output:
// make: Honda
// model: Civic
// year: 2023
Explanation: Inside a for...in
loop, the key
is a variable that holds the property name on each iteration. Bracket notation is essential here to access the corresponding value dynamically.
Example 7: Property Keys Starting with a Number
// Define an object with a property key starting with a number
const report = {
"1st-quarter": "Success"
};
// Access the property using bracket notation
console.log(report["1st-quarter"]); // Output: Success
Explanation: Property keys that start with a number are not valid identifiers for dot notation. Bracket notation is the correct way to access such properties.
When to use which
Choosing between dot and bracket notation often comes down to the specific use case and the nature of the property key.
Use Dot Notation when the property key is a valid JavaScript identifier. It is generally more readable and concise for static property access.
Use Bracket Notation when the property key is not a valid identifier (e.g., contains spaces, hyphens, or starts with a number). It is also necessary when the property name is dynamic, meaning it is stored in a variable or determined at runtime.
By mastering both notations, you can write more flexible and robust JavaScript code.