Object properties are fundamental components of JavaScript objects. They store data and define the characteristics of an object. Understanding how to work with object properties is crucial for effective JavaScript programming.
In JavaScript, object properties are key-value pairs that belong to an object. The key is always a string (or a Symbol), while the value can be any valid JavaScript data type, including other objects or functions.
There are two main ways to access object properties:
object.propertyName
object['propertyName']
Here's an example demonstrating both methods:
const person = {
name: 'John Doe',
age: 30
};
console.log(person.name); // Output: John Doe
console.log(person['age']); // Output: 30
You can easily add new properties or modify existing ones:
person.job = 'Developer'; // Adding a new property
person['age'] = 31; // Modifying an existing property
console.log(person);
// Output: { name: 'John Doe', age: 31, job: 'Developer' }
JavaScript object properties can be categorized into two main types:
const person = {
firstName: 'John',
lastName: 'Doe',
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(value) {
[this.firstName, this.lastName] = value.split(' ');
}
};
console.log(person.fullName); // Output: John Doe
person.fullName = 'Jane Smith';
console.log(person.firstName); // Output: Jane
console.log(person.lastName); // Output: Smith
Each property has attributes that define its behavior:
You can use Object.defineProperty()
to set these attributes:
const obj = {};
Object.defineProperty(obj, 'readOnly', {
value: 42,
writable: false
});
obj.readOnly = 100; // This won't change the value
console.log(obj.readOnly); // Output: 42
Object.keys()
, Object.values()
, or Object.entries()
for efficient property iteration.Object.freeze()
or Object.seal()
to control object mutability.To deepen your understanding of JavaScript objects and their properties, explore these related topics:
Mastering object properties is essential for effective JavaScript programming. They form the backbone of data structures in JavaScript and are crucial for working with complex data in your applications.