JAVASCRIPT· LESSON 03
Understanding Objects
Learn how JavaScript objects store data as key-value pairs, and how to access, modify, and add methods to them.
Objects are a common way to store data, but unlike arrays, they don’t use numbered indexes — they use keys and values.
{ name: "Sallu bhai" }
Here, name is the key, and "Sallu bhai" is the value.
Creating an Object
const student = {
name: "Sallu",
status: "unmarried",
favAnimal: "blackbuck",
courses: ["driving", "acting"]
};
Accessing Object Properties
To access an object’s data, we use dot notation (.).
console.log(student.status); // "unmarried"
console.log(student.courses[0]); // "driving"
Adding and Modifying Properties
Objects are mutable — you can add new keys or change existing ones.
const car = { brand: "Mahindra", model: "XUV" };
// Modify an existing property
car.model = "Thar";
// Add a new property
car.year = 2022;
console.log(car); // { brand: "Mahindra", model: "Thar", year: 2022 }
Nested Objects
Objects can contain other objects. This is useful when you want to group related information together.
const student = {
name: "Alex",
age: 20,
address: {
city: "Noida",
pincode: 201301
}
};
console.log(student.name); // "Alex"
console.log(student.address.city); // "Noida"
console.log(student.address.pincode); // 201301
Methods in Objects
Objects can also hold functions. When a function belongs to an object, we call it a method.
const user = {
username: "coder123",
greet: function () {
console.log(`Hello, welcome back ${this.username}!`);
}
};
user.greet(); // "Hello, welcome back coder123!"
Try it yourself
- Profile Builder: Create an object named
smartphonewith keys forbrand,model,storage, andprice. Print a sentence using these values (e.g., “I have a 128GB iPhone.”). - Property Mutation: Update
smartphone’spriceto a lower value, and add a new boolean property calledis5G. - Object Method: Create an object named
calculatorwith propertiesnum1andnum2, and a method calledaddthat returns their sum usingthis.
