JavaScript Object Properties
JavaScript objects consist of properties and methods. Properties are key-value pairs where the key is a string and the value can be any data type. Understanding object properties is crucial for working effectively with objects in JavaScript.
1. Accessing Properties
You can access object properties using either dot notation or bracket notation.
Dot Notation
const person = {
name: "Alice",
age: 25
};
console.log(person.name); // Alice
Bracket Notation
const person = {
name: "Alice",
age: 25
};
console.log(person["age"]); // 25
Bracket notation is useful when the property name is dynamic or not a valid identifier.
2. Modifying Properties
You can modify properties using both dot notation and bracket notation in a similar way to accessing them.
Dot Notation
const person = {
name: "Alice",
age: 25
};
person.age = 26;
console.log(person.age); // 26
Bracket Notation
const person = {
name: "Alice",
age: 25
};
person["age"] = 26;
console.log(person["age"]); // 26
3. Adding Properties
New properties can be added to objects dynamically.
const person = {
name: "Alice"
};
person.age = 25;
console.log(person.age); // 25
4. Deleting Properties
Properties can be removed from objects using the delete
operator.
const person = {
name: "Alice",
age: 25
};
delete person.age;
console.log(person.age); // undefined
5. Property Attributes
JavaScript object properties have attributes like writable
, enumerable
, and configurable
. You can view and modify these attributes using Object.getOwnPropertyDescriptor
and Object.defineProperty
.
Viewing Property Attributes
const person = {
name: "Alice"
};
const descriptor = Object.getOwnPropertyDescriptor(person, "name");
console.log(descriptor);
Modifying Property Attributes
const person = {
name: "Alice"
};
Object.defineProperty(person, "name", {
writable: false
});
person.name = "Bob"; // This will not change the name property
console.log(person.name); // Alice