Object
JavaScript objects store key-value pairs. Learn to access properties with dot and bracket notation, set and delete values, and use functions as methods.
JavaScript objects store key-value pairs. Learn to access properties with dot and bracket notation, set and delete values, and use functions as methods.
An object groups related data together as key-value pairs. Think of it as a container with labeled slots.
const person = { name: "Reza", age: 28, city: "Jakarta",};Keys are strings (or symbols). Values can be anything.
Dot notation — the clean way when you know the key name:
person.name; // 'Reza'person.age; // 28Bracket notation — required when the key is dynamic or has special characters:
person["name"]; // 'Reza'
const key = "city";person[key]; // 'Jakarta'
person["my-key"]; // works — dot notation can't handle hyphensperson.email = "reza@example.com"; // add new propertyperson.age = 29; // update existingdelete person.city;A method is a function stored as an object property:
const person = { name: "Reza", greet() { console.log(`Hi, I'm ${this.name}`); },};
person.greet(); // Hi, I'm Rezathis inside a method refers to the object the method belongs to.
"name" in person; // trueperson.hasOwnProperty("email"); // falsefor (const key in person) { console.log(`${key}: ${person[key]}`);}Or get all keys as an array:
Object.keys(person); // ['name', 'age']Object.values(person); // ['Reza', 28]Object.entries(person); // [['name', 'Reza'], ['age', 28]]