Accessing and Modifying Properties
Concepts:
- Properties: Attributes associated with an object that hold specific values.
- Dot Notation: Uses a period (.) to access properties, e.g.,
object.property
.
- Bracket Notation: Uses square brackets [] to access properties, e.g.,
object['property']
.
Steps:
Accessing Values:
- Use dot notation or bracket notation to retrieve a property's value.
- For example, to get the
name
property of the person
object using dot notation: person.name
- To get the
age
property of the person
object using bracket notation: person['age']
Modifying Values:
- Use dot notation or bracket notation to update a property's value.
- Assign a new value to the property using the
=
operator.
- For example, to change the
name
property of the person
object to "John" using dot notation: person.name = "John"
- To change the
age
property of the person
object to 25 using bracket notation: person['age'] = 25
JavaScript Example:
// Define an object
const person = {
name: "Alice",
age: 22
}
// Accessing Properties
console.log(person.name); // Output: Alice
console.log(person['age']); // Output: 22
// Modifying Properties
person.name = "Bob";
person['age'] = 23;
// Output the modified values
console.log(person.name); // Output: Bob
console.log(person['age']); // Output: 23
Tips for Accessibility and Ease of Use:
- Use meaningful property names to make code more readable.
- Consider using constants for property names to prevent accidental modifications.
- Avoid using dot notation when accessing properties with special characters or spaces. In these cases, bracket notation is more suitable.