In the previous tutorial, you learned how to store a list of values in an array. But what if you want to describe one real thing, like a student with a name, age, city and email? An array is not the best choice for that. This is where JavaScript Objects come in. An object stores related data together using names (keys) and values.
What is an Object?
Think of an ID card. It has labels (Name, Age, City) and values next to each label (Ali, 22, Karachi). An object works the same way.
Without an object, you need many separate variables:
let studentName = "Ali";
let studentAge = 22;
let studentCity = "Karachi";
let isEnrolled = true;
With an object, everything stays in one place:
let student = {
name: "Ali",
age: 22,
city: "Karachi",
isEnrolled: true
};
console.log(student);
Cleaner and easier to manage. That is why JavaScript Objects are used everywhere, from user profiles to products and orders.
1. Creating an Object
Use curly braces { }. Inside, write key: value pairs separated by commas.
// Syntax
// let objectName = {
// key1: value1,
// key2: value2
// };
let car = {
brand: "Toyota",
model: "Corolla",
year: 2022,
isElectric: false
};
let emptyObject = {};
console.log(car);
console.log(emptyObject);
Each key: value pair is called a property. A value can be any data type: string, number, boolean, array, or even another object.
2. Accessing Object Properties
There are two ways to read a value.
Dot notation (most common)
let student = {
name: "Ayesha",
age: 21,
city: "Lahore"
};
console.log(student.name); // Ayesha
console.log(student.age); // 21
console.log(student.phone); // undefined (no such property)
Bracket notation
console.log(student["name"]); // Ayesha
console.log(student["city"]); // Lahore
// Useful when the key is stored in a variable
let key = "age";
console.log(student[key]); // 21
Use dot notation in most cases. Use bracket notation when the key is dynamic (stored in a variable) or has spaces like student["full name"].
3. Changing, Adding and Deleting Properties
let student = {
name: "Bilal",
age: 20
};
// Change a value
student.age = 21;
// Add a new property
student.city = "Karachi";
student["email"] = "bilal@example.com";
console.log(student);
// { name: "Bilal", age: 21, city: "Karachi", email: "bilal@example.com" }
// Delete a property
delete student.email;
console.log(student);
// { name: "Bilal", age: 21, city: "Karachi" }
Just like arrays, if you create an object with const, you can still change its properties. You only cannot assign a whole new object to that variable.
const user = { name: "Ali" };
user.name = "Hamza"; // allowed
user.age = 25; // allowed
user = { name: "Sara" }; // Error: Assignment to constant variable
4. Checking if a Property Exists
let student = {
name: "Ali",
age: 22
};
console.log("name" in student); // true
console.log("phone" in student); // false
console.log(student.hasOwnProperty("age")); // true
console.log(student.phone !== undefined); // false
// Real use: check before using
if ("age" in student) {
console.log("Age is " + student.age);
}
5. Object Methods (Functions Inside Objects)
A property can also store a function. A function inside an object is called a method.
let student = {
name: "Ali",
age: 22,
greet: function () {
console.log("Hello, I am Ali");
},
// shorter way (modern)
sayAge() {
console.log("I am 22 years old");
}
};
student.greet(); // Hello, I am Ali
student.sayAge(); // I am 22 years old
6. The this Keyword
Inside a method, this means “the object that owns this method”. It lets the method read the object’s own properties.
let student = {
name: "Ayesha",
age: 21,
city: "Lahore",
introduce() {
console.log("My name is " + this.name + ", I am " + this.age + " years old from " + this.city);
},
birthday() {
this.age++;
console.log("Happy Birthday! Now I am " + this.age);
}
};
student.introduce();
// My name is Ayesha, I am 21 years old from Lahore
student.birthday();
// Happy Birthday! Now I am 22
student.introduce();
// My name is Ayesha, I am 22 years old from Lahore
Important: do not use arrow functions as object methods when you need this. Arrow functions handle this differently, and we will study this in detail in the Advanced series.
7. Nested Objects (Object Inside Object)
A property can contain another object. This is very common in real data.
let employee = {
name: "Usman",
position: "Developer",
address: {
city: "Karachi",
area: "Gulshan",
zip: 75300
},
skills: ["HTML", "CSS", "JavaScript"]
};
console.log(employee.address.city); // Karachi
console.log(employee.address.zip); // 75300
console.log(employee.skills[2]); // JavaScript
console.log(employee["address"]["area"]); // Gulshan
// Change a nested value
employee.address.city = "Lahore";
console.log(employee.address.city); // Lahore
// Add to a nested array
employee.skills.push("PHP");
console.log(employee.skills); // ["HTML", "CSS", "JavaScript", "PHP"]
8. Looping Through an Object
You learned for...in in the loops tutorial. Here are the 3 common ways to loop through JavaScript Objects.
let student = {
name: "Ali",
age: 22,
city: "Karachi"
};
// Way 1: for...in (keys)
for (let key in student) {
console.log(key + ": " + student[key]);
}
// Way 2: Object.keys() (array of keys)
console.log(Object.keys(student)); // ["name", "age", "city"]
// Way 3: Object.values() (array of values)
console.log(Object.values(student)); // ["Ali", 22, "Karachi"]
// Bonus: Object.entries() (array of [key, value] pairs)
console.log(Object.entries(student));
// [["name", "Ali"], ["age", 22], ["city", "Karachi"]]
for (let [key, value] of Object.entries(student)) {
console.log(key + " = " + value);
}
Counting properties of an object:
console.log(Object.keys(student).length); // 3
9. Array of Objects (Most Used in Real Projects)
When you build real apps, data usually comes as an array of objects, for example from a database or an API.
let students = [
{ name: "Ali", marks: 78, city: "Karachi" },
{ name: "Sara", marks: 92, city: "Lahore" },
{ name: "Bilal", marks: 45, city: "Karachi" },
{ name: "Ayesha", marks: 66, city: "Islamabad" }
];
// Access one student
console.log(students[1].name); // Sara
// Print all students
for (let student of students) {
console.log(student.name + " scored " + student.marks);
}
// Find the topper
let topper = students[0];
for (let student of students) {
if (student.marks > topper.marks) {
topper = student;
}
}
console.log("Topper: " + topper.name + " (" + topper.marks + ")");
// Topper: Sara (92)
// Add a new student
students.push({ name: "Usman", marks: 88, city: "Karachi" });
console.log(students.length); // 5
// Count students from Karachi
let karachiCount = 0;
for (let student of students) {
if (student.city === "Karachi") {
karachiCount++;
}
}
console.log("Karachi students: " + karachiCount); // 3
10. Copying Objects (Important!)
Objects are reference types, just like arrays. If you assign one object to another variable, both share the same data.
let user1 = { name: "Ali", age: 22 };
let user2 = user1; // NOT a real copy
user2.name = "Bilal";
console.log(user1.name); // Bilal (original changed!)
console.log(user2.name); // Bilal
To make a real, independent copy:
let user1 = { name: "Ali", age: 22 };
let copy1 = Object.assign({}, user1); // way 1
let copy2 = { ...user1 }; // way 2 (spread, ES6)
copy1.name = "Sara";
copy2.name = "Hina";
console.log(user1.name); // Ali (safe)
console.log(copy1.name); // Sara
console.log(copy2.name); // Hina
Note: these copies are “shallow”. Nested objects inside are still shared. For a full copy of nested data, you can use structuredClone():
let employee = { name: "Usman", address: { city: "Karachi" } };
let deepCopy = structuredClone(employee);
deepCopy.address.city = "Lahore";
console.log(employee.address.city); // Karachi (safe)
console.log(deepCopy.address.city); // Lahore
11. Converting Objects to JSON (Quick Preview)
When sending data to a server, objects are converted to text called JSON. We will study JSON fully in the Advanced series, but here is a small preview:
let student = { name: "Ali", age: 22 };
let text = JSON.stringify(student);
console.log(text); // {"name":"Ali","age":22}
console.log(typeof text); // string
let backToObject = JSON.parse(text);
console.log(backToObject.name); // Ali
Practical Example 1: Product Object With Methods
let product = {
name: "Laptop",
price: 85000,
quantity: 3,
discountPercent: 10,
getTotal() {
return this.price * this.quantity;
},
getDiscount() {
return this.getTotal() * this.discountPercent / 100;
},
getFinalAmount() {
return this.getTotal() - this.getDiscount();
}
};
console.log("Total: " + product.getTotal()); // 255000
console.log("Discount: " + product.getDiscount()); // 25500
console.log("Final: " + product.getFinalAmount()); // 229500
Practical Example 2: Bank Account
let account = {
owner: "Ali",
balance: 10000,
deposit(amount) {
if (amount <= 0) {
console.log("Invalid amount");
return;
}
this.balance += amount;
console.log("Deposited " + amount + ". Balance: " + this.balance);
},
withdraw(amount) {
if (amount > this.balance) {
console.log("Insufficient balance");
return;
}
this.balance -= amount;
console.log("Withdrew " + amount + ". Balance: " + this.balance);
}
};
account.deposit(5000); // Deposited 5000. Balance: 15000
account.withdraw(3000); // Withdrew 3000. Balance: 12000
account.withdraw(50000); // Insufficient balance
Practical Example 3: Contact Book
let contacts = [
{ name: "Ali", phone: "0300-1111111" },
{ name: "Sara", phone: "0321-2222222" },
{ name: "Bilal", phone: "0333-3333333" }
];
function findContact(searchName) {
for (let contact of contacts) {
if (contact.name.toLowerCase() === searchName.toLowerCase()) {
return contact;
}
}
return null;
}
let result = findContact("sara");
if (result) {
console.log("Found: " + result.name + " - " + result.phone);
} else {
console.log("Contact not found");
}
// Found: Sara - 0321-2222222
Practical Example 4: Show Objects on a Webpage
<div id="cards"></div>
<script>
let courses = [
{ title: "HTML", lessons: 8 },
{ title: "CSS", lessons: 10 },
{ title: "JavaScript", lessons: 47 }
];
let html = "";
for (let course of courses) {
html += "<p>" + course.title + " - " + course.lessons + " lessons</p>";
}
document.getElementById("cards").innerHTML = html;
</script>
We will learn document.getElementById properly in the DOM tutorials.
Array vs Object: When to Use Which?
| Use an Array when | Use an Object when |
|---|---|
| You have a list of similar items | You describe one thing with many details |
| Order and index matter | Names (keys) matter |
| Example: list of cities | Example: one student’s profile |
["Ali", "Sara", "Bilal"] |
{ name: "Ali", age: 22 } |
Common Mistakes to Avoid
let student = { name: "Ali", age: 22 };
// Mistake 1: using a key that does not exist
console.log(student.Name); // undefined (keys are case-sensitive)
// Mistake 2: forgetting quotes in bracket notation
// console.log(student[name]); WRONG: looks for a variable called name
console.log(student["name"]); // CORRECT
// Mistake 3: reading a nested property that does not exist
let user = { name: "Ali" };
// console.log(user.address.city); Error: Cannot read properties of undefined
console.log(user.address?.city); // undefined (safe way with ?.)
// Mistake 4: using = to copy an object (it shares the same data)
let copy = student; // WRONG
let realCopy = { ...student }; // CORRECT
Quick Recap
- An object stores data as
key: valuepairs inside{ } - Read values with dot notation
obj.nameor bracket notationobj["name"] - You can add, change and delete properties any time
- A function inside an object is a method, and
thispoints to the object itself - Use
for...in,Object.keys(),Object.values()andObject.entries()to loop - Arrays of objects are the most common data format in real projects
- Objects are reference types, so use
{ ...obj }to copy
Excellent work! You now understand JavaScript Objects, one of the most important topics in the language. Together with arrays, you can now represent almost any real-world data.
Practice Exercises
- Create an object
myProfilewith name, age, city and hobby. Print each property using dot notation. - Add a new property
emailand change theage. Print the object again. - Delete the
hobbyproperty and print the object. - Create an object
bookwith title, author, price and a methodgetInfo()that prints “Title by Author – Rs. Price” usingthis. - Create a
rectangleobject with width and height, and a methodgetArea()that returns the area. - Loop through your
myProfileobject and print every key and value. - Create an object with a nested
addressobject (city, country). Print the city. - Create an array of 4 product objects (name, price). Print the name of the most expensive product.
- Make a real copy of an object, change the copy, and prove that the original did not change.
- Count how many properties your object has using
Object.keys().
Assignment
Build a Student Management System:
- Create an array
studentswith 5 student objects. Each student has:name,marks(object withmath,science,english), andcity. - Create a function
getTotal(student)that returns the total of the 3 subjects. - Create a function
getPercentage(student)that returns the percentage out of 300. - Create a function
getGrade(percentage)that returns A+ (90 and above), A (80 and above), B (70 and above), C (60 and above), D (50 and above) or F. - Loop through all students and print a report card for each:
Name: Ali
City: Karachi
Total: 240 / 300
Percentage: 80%
Grade: A
- Find and print the topper (highest total).
- Add a new student using
push()and print the total number of students.
Bonus Challenge
Create a shoppingCart object with an items array (each item has name, price, quantity) and these methods: addItem(item), removeItem(name), getTotal() and showCart(). Use this inside the methods. Test it by adding 3 items, removing 1, and printing the final cart and total.
What’s Next?
In the next tutorial, we will learn JavaScript String Methods. You will learn how to change, search and clean text, which is very useful when working with names, emails and form data stored in your JavaScript Objects.
Missed the last tutorial? Go back to JavaScript Arrays, or browse the full JavaScript Tutorial Series. For deeper reference, see the MDN guide to working with objects.

