How to Work with Object Properties in Object-Oriented JavaScript?

Estimated read time 1 min read

Properties are characteristics of an object in object-oriented JavaScript. Here’s how you can work with object properties:

  1. Accessing properties: You can access an object’s properties using the dot (.) or bracket ([]) notation. The dot notation is used for properties with valid identifier names, while the bracket notation can be used for any string expression.
  2. Adding/updating properties: You can add or update properties of an object using the assignment operator (=). You can use either the dot or bracket notation to access the properties.
  3. Deleting properties: You can delete properties from an object using the delete operator.
  4. Enumerating properties: You can enumerate all the properties of an object using for...in loop or Object.keys() method.

Here is an example of accessing, adding/updating, deleting, and enumerating object properties in JavaScript:

const person = {
  name: 'John',
  age: 30
};

// Accessing properties
console.log(person.name); // John
console.log(person['age']); // 30

// Adding/updating properties
person.email = 'john@example.com';
person['phone'] = '555-555-5555';

// Deleting properties
delete person.email;

// Enumerating properties
for (const property in person) {
  console.log(`${property}: ${person[property]}`);
}

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply