HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Object Properties

Properties are the most important part of any JavaScript object. They store the data associated with an object. In this lesson, we will learn how to manipulate these properties dynamically.


Adding and Deleting Properties

Objects in JavaScript are dynamic. You can add new properties or delete existing ones at any time.

Adding a Property:

const person = {
  firstName: "Mim",
  lastName: "Akter"
};

person.nationality = "Bangladeshi"; 
// Now person has a third property

Deleting a Property:

The delete keyword removes a property from an object.

const person = {
  firstName: "Mim",
  age: 25
};

delete person.age; 
// age is now removed from the object

Nested Objects

Properties of an object can themselves be objects. This allows you to create complex data structures.

const person = {
  name: "Mim",
  age: 25,
  address: {
    city: "Dhaka",
    area: "Mirpur",
    zip: 1216
  }
};

console.log(person.address.city); // "Dhaka"

Iterating Properties (for...in)

You can loop through all the properties of an object using the for...in loop.

const person = {
  fname: "Mim",
  lname: "Akter",
  age: 25
};

let text = "";
for (let x in person) {
  text += person[x] + " ";
}

console.log(text); // "Mim Akter 25 "
Tip: Inside a for...in loop, you must use bracket notation (person[x]) to access the value, because the variable x holds the property name as a string.

Key Points to Remember

  • Properties can be added by simply assigning a value (obj.prop = value)
  • The delete keyword removes both the value and the property itself
  • Objects can be nested to any depth
  • Use the for...in loop to navigate through all properties
  • Property names in JS are case-sensitive
  • Properties are technically just "keys" in a key-value pair store