6️⃣ Objects in JavaScript (Simple + Practical)


🔹 What is an Object?

An object is a collection of data stored in key-value pairs.

👉 Real-life example:
A student has name, age, marks → all grouped together.

let student = {
name: "Aditya",
age: 20,
marks: 85
};

🔹 Object Properties

Properties are variables inside an object.

let student = {
name: "Aditya",
age: 20
};console.log(student.name); // Aditya
console.log(student["age"]); // 20

👉 Two ways to access:

  • Dot notation → student.name
  • Bracket notation → student["name"]

🔹 Object Methods

Methods are functions inside an object.

let student = {
name: "Aditya",
greet: function() {
return "Hello " + this.name;
}
};console.log(student.greet()); // Hello Aditya

👉 this refers to the current object.


🔹 Nested Objects

Objects inside another object.

let student = {
name: "Aditya",
address: {
city: "Delhi",
pincode: 110001
}
};console.log(student.address.city); // Delhi

🔹 Object.keys()

Returns all keys (property names) in an array.

let student = {
name: "Aditya",
age: 20
};console.log(Object.keys(student));
// ["name", "age"]

🔹 Object.values()

Returns all values in an array.

console.log(Object.values(student));
// ["Aditya", 20]

🔹 Object.entries()

Returns key-value pairs as arrays.

console.log(Object.entries(student));
// [["name", "Aditya"], ["age", 20]]

🧠 Practice: Student Management System

🎯 Goal:

Store and manage student data using objects.


✅ Example:

let student = {
name: "Rahul",
age: 21,
marks: {
math: 80,
science: 75,
english: 85
},
getTotal: function() {
return this.marks.math + this.marks.science + this.marks.english;
}
};// Access data
console.log(student.name);// Nested object
console.log(student.marks.math);// Method
console.log("Total Marks:", student.getTotal());// Keys, values, entries
console.log(Object.keys(student));
console.log(Object.values(student));
console.log(Object.entries(student));

🚀 Mini Project (Multiple Students)

let students = [
{
name: "Amit",
age: 20,
marks: 80
},
{
name: "Priya",
age: 22,
marks: 90
}
];// Loop through students
students.forEach(function(stu) {
console.log(stu.name + " - " + stu.marks);
});

🔥 Practice Tasks for Students

  1. Create an object for 5 students
  2. Add a method to calculate average marks
  3. Print all student names using Object.keys()
  4. Find student with highest marks
  5. Add nested object for address