Last updated
JavaScript Objects
Definition: An object groups related data as key:value pairs. It is ideal for describing one "thing" with several properties — a user, a product, a car.
let person = {
name: "Sam",
age: 25,
city: "London"
};
console.log(person);
Example 1 — reading properties
console.log(person.name); // Sam (dot notation) console.log(person["age"]); // 25 (bracket notation)
Example 2 — changing and adding
person.age = 26; // change person.email = "sam@mail.com"; // add new console.log(person);
Example 3 — methods (functions inside objects)
Inside a method, this refers to the object itself:
let user = {
name: "Sam",
greet: function() {
console.log("Hi, I am " + this.name);
}
};
user.greet();
Example 4 — array of objects (very common)
let people = [
{name: "Sam", age: 25},
{name: "Alex", age: 30}
];
console.log(people[1].name); // Alex
💡 Arrays vs objects: arrays hold values by position; objects hold values by name. Combine them to model real data.
Try it Yourself
Output
Ad · responsive