Learn how to read, update, add, and delete properties of JavaScript objects using dot notation and bracket notation.
JavaScript provides two main ways to access properties in an object:
let user = {
name: "Liam",
age: 30
};
console.log(user.name); // Output: Liam
console.log(user.age); // Output: 30
console.log(user["name"]); // Output: Liam
let key = "age";
console.log(user[key]); // Output: 30
let person = {
"first name": "Anna"
};
console.log(person["first name"]); // Output: Anna
You can change the value of a property using either notation:
user.age = 31;
user["name"] = "Noah";
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
}
Use the delete
keyword:
delete user.age;
console.log(user);
// Output: { name: "Noah", email: "liam@example.com", isMember: true }
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);
if (key in object)
or object.hasOwnProperty(key)
)