Syntax
const obj = { key: value, method() { } };Examples
Creating and Accessing Objects
Basic object creation and property access.
const person = {
name: "Alice",
age: 25,
greet() {
console.log(`Hi, I am ${this.name}`);
}
};
console.log(person.name); // dot notation - "Alice"
console.log(person["age"]); // bracket notation - 25
person.greet(); // "Hi, I am Alice"Modifying and Deleting Properties
Adding, updating, and removing object properties.
const car = { make: "Toyota", model: "Corolla" };
car.year = 2024; // adding a new property
car.model = "Camry"; // updating an existing property
delete car.make; // removing a property
console.log(car); // { model: "Camry", year: 2024 }Bracket Notation for Dynamic Keys
Using bracket notation when the property name is stored in a variable.
const user = { name: "Bob", email: "bob@example.com" };
const field = "email";
console.log(user[field]); // "bob@example.com"
// user.field would look for a literal property named "field" - wrong!Best practices
- Use dot notation when the property name is a fixed, known identifier; use bracket notation when it is dynamic or stored in a variable
- Prefer object shorthand syntax ({ name, age } instead of { name: name, age: age }) when variable names match property names
- Use methods shorthand (greet() { } instead of greet: function() { }) for cleaner object method definitions
- Be careful with delete - it is relatively slow and often better replaced by restructuring data or using Map for frequently changing key sets
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification