JavaScript Object Properties
Object properties are key-value pairs associated with an object. Each property has a key (also known as a name or identifier) and a corresponding value. Here are some common operations you can perform with object properties:
Accessing Object Properties
You can access object properties using dot notation or bracket notation.
Example:
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
// Dot notation
console.log(person.firstName); // Output: John
// Bracket notation
console.log(person["lastName"]); // Output: Doe
Adding and Modifying Properties
You can add new properties to an object or modify existing ones by assigning values to them.
Example:
// Adding a new property
person.email = "john@example.com";
// Modifying an existing property
person.age = 31;
Deleting Properties
You can remove a property from an object using the delete
keyword.
Example:
delete person.age;
Property Existence Check
You can check if a property exists in an object using the in
operator or the hasOwnProperty()
method.
Example:
// Using the "in" operator
if ("age" in person) {
console.log("Age property exists.");
} else {
console.log("Age property does not exist.");
}
// Using the hasOwnProperty() method
if (person.hasOwnProperty("age")) {
console.log("Age property exists.");
} else {
console.log("Age property does not exist.");
}
Enumerating Properties
You can loop through the properties of an object using a for...in
loop.
Example:
for (let key in person) {
console.log(key + ": " + person[key]);
}
Understanding how to work with object properties is essential for manipulating and managing objects effectively in JavaScript.