JavaScript Object Properties
14 April 2025 | Category: JavaScript
In JavaScript, objects are collections of properties, where each property is a key-value pair. Properties define the characteristics and behavior of objects.
🔑 What Is a Property?
A property is an association between a key (name) and a value.
const person = {
name: "Alice", // 'name' is a property with the value "Alice"
age: 25
};
name
andage
are keys (also called property names)."Alice"
and25
are the values associated with those keys.
📦 Property Types
There are two main types of object properties:
1. Data Properties
These store values (like strings, numbers, objects, etc.)
const user = {
username: "devin",
score: 100
};
2. Accessor Properties
These are defined using getters and setters.
const profile = {
firstName: "John",
lastName: "Doe",
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(profile.fullName); // John Doe
đź› Ways to Access Object Properties
1. Dot Notation
console.log(person.name); // "Alice"
2. Bracket Notation
console.log(person["name"]); // "Alice"
đź”” Use bracket notation when the property name is dynamic or contains special characters.
âž• Adding and Updating Properties
person.location = "USA"; // Add new
person.age = 30; // Update existing
❌ Deleting Properties
delete person.age; // Removes the 'age' property
🔍 Checking Property Existence
Using in
operator
"name" in person; // true
Using hasOwnProperty()
person.hasOwnProperty("name"); // true
đź§® Enumerating Object Properties
Object.keys()
Returns an array of keys.
Object.keys(person); // ["name", "location"]
Object.values()
Returns an array of values.
Object.values(person); // ["Alice", "USA"]
Object.entries()
Returns an array of key-value pairs.
Object.entries(person); // [["name", "Alice"], ["location", "USA"]]
đź§° Property Descriptors
Each property in an object has attributes that control its behavior:
writable
: Can be changed.enumerable
: Shows up in loops.configurable
: Can be deleted or modified.
You can define properties more precisely with Object.defineProperty()
:
Object.defineProperty(person, "gender", {
value: "female",
writable: false,
enumerable: true,
configurable: false
});
đź§Ľ Best Practices
- Use dot notation for readability.
- Use bracket notation for dynamic keys.
- Avoid overwriting built-in object properties.
- Use
const
when declaring objects (you can still change properties).