Objects
Group related data under one name — the structure that models real things like users, products and posts.
What you will learn
- Create objects with properties
- Read and change properties
- Add methods to objects
Key-value pairs
An object groups related data as key: value pairs inside { }. Read a value with dot notation.
<script>
const user = {
name: "Asha",
age: 22,
city: "Bengaluru",
isStudent: true
};
document.write(user.name + " is " + user.age + " from " + user.city);
</script>The user object bundles four facts about one person, each as a key: value pair. We then pull values out with dot notation: user.name gives "Asha", user.age gives 22, user.city gives "Bengaluru", and we join them into a sentence.
Note: Output: Asha is 22 from Bengaluru
Read, change, add
<script>
const car = { brand: "Tata", year: 2024 };
document.write(car.brand + "<br>");
car.year = 2025; // change
car.color = "blue"; // add new property
document.write(car.year + " " + car.color);
</script>First car.brand reads "Tata". Then car.year = 2025 changes an existing property. Then car.color = "blue" adds a brand-new property that was not there before. The final line reads both updated values back out.
These are the everyday operations on an object — reading a value, changing one, and adding one. Here they are as numbered steps:
- Create the object:
const car = { brand: "Tata", year: 2024 }stores two properties to start with. - Read a property:
car.brandfetches the current value, "Tata". - Update a property:
car.year = 2025overwrites the existingyearwith a new value. - Add a property:
car.color = "blue"creates a brand-newcolorkey that did not exist before. - Read again:
car.yearandcar.colornow show the updated and newly added values.
Note: Output:
Tata
2025 blue
(Note: even though car is a const, we can still change what is inside it. const only stops the whole car from being replaced.)
Methods — functions inside objects
A property can also be a function. That is called a method, and inside it the keyword this refers back to the object it belongs to.
<script>
const person = {
name: "Ravi",
greet() { return "Hi, I am " + this.name; }
};
document.write(person.greet());
</script>Calling person.greet() runs the method. Inside it, this.name means "the name of this object", which is "Ravi". So it returns and prints "Hi, I am Ravi".
Note: Output: Hi, I am Ravi
Note: Objects and arrays combine to model anything: an array of objects is how you store a list of users, products or posts — exactly the shape of data in databases and APIs (an API is a way for two programs, such as a website and a server, to talk to each other and swap data).
Q. How do you read the name property of an object called user?
✍️ Practice
- Create an object describing yourself with at least four properties, then print them.
- Add a
greet()method that returns a sentence usingthis.
🏠 Homework
- Make an array of three product objects (name, price) and loop to print each one.