Lesson 6: Accessing and Updating Object Properties

Lesson Goal:

Learn how to read, update, add, and delete properties of JavaScript objects using dot notation and bracket notation.


Accessing Object Properties

JavaScript provides two main ways to access properties in an object:


Dot Notation

let user = {
  name: "Liam",
  age: 30
};

console.log(user.name);  // Output: Liam
console.log(user.age);   // Output: 30
  • Use when you know the exact property name
  • Clean and readable

Bracket Notation

console.log(user["name"]);  // Output: Liam

let key = "age";
console.log(user[key]);     // Output: 30
  • Use when the key is stored in a variable
  • Needed if the property name includes spaces or special characters
let person = {
  "first name": "Anna"
};

console.log(person["first name"]);  // Output: Anna

Updating Properties

You can change the value of a property using either notation:

user.age = 31;
user["name"] = "Noah";

Adding New Properties

You can add new key-value pairs to an object at any time:

user.email = "liam@example.com";
user["isMember"] = true;

Now the object becomes:

{
  name: "Noah",
  age: 31,
  email: "liam@example.com",
  isMember: true
}

Deleting Properties

Use the delete keyword:

delete user.age;
console.log(user);  
// Output: { name: "Noah", email: "liam@example.com", isMember: true }

Try It Yourself

let car = {
  brand: "Toyota",
  year: 2020
};

// Access values
console.log(car.brand);

// Update value
car.year = 2023;

// Add new property
car.color = "red";

// Delete a property
delete car.brand;

console.log(car);

Tips and Best Practices

  • Use dot notation whenever possible for readability
  • Use bracket notation when using dynamic keys or keys with spaces
  • Always check if a key exists before using it (optional: if (key in object) or object.hasOwnProperty(key))