JavaScript Objects
An object groups related values together under one name.
Real Life Objects
A mobile phone is an object. It has properties like brand, colour and price, and it has actions like call and send message. JavaScript objects work the same way: properties are values, and actions are functions called methods.
Creating an Object
Write the properties as name: value pairs inside curly brackets:
Example
const phone = {
brand: "Samsung",
model: "A15",
price: 42000,
inStock: true
};Reading Properties
There are two ways to read a property:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const student = {
name: "Ayesha Siddiqui",
course: "Web Development",
rollNo: 117
};
document.getElementById("demo").innerHTML =
student.name + " studies " + student["course"] + " (Roll no " + student.rollNo + ")";
</script>
</body>
</html>Try it Yourself »Ayesha Siddiqui studies Web Development (Roll no 117)
| Syntax | When to use |
|---|---|
object.property | Normal use, short and clear |
object["property"] | When the name is in a variable or has spaces |
Changing, Adding and Deleting
Example
const product = { name: "Kurta", price: 2500 };
product.price = 2200; // change
product.size = "M"; // add
delete product.name; // delete
console.log(product);{ price: 2200, size: 'M' }A const object can still have its properties changed. const only stops you from replacing the whole object with a new one.
Methods and this
A method is a function stored in an object. Inside a method, this means "this object".
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const cart = {
owner: "Ali",
items: 3,
pricePerItem: 450,
total: function () {
return this.items * this.pricePerItem;
}
};
document.getElementById("demo").innerHTML = cart.owner + "'s total is Rs " + cart.total();
</script>
</body>
</html>Try it Yourself »Ali's total is Rs 1350
Call a method with brackets: cart.total(). Without brackets you get the function itself, not its result.
Objects Inside Objects
A property can hold another object or an array:
Example
const shop = {
name: "Rehman Electronics",
address: { area: "Orangi Town", city: "Karachi" },
categories: ["Fans", "Irons", "Mixers"]
};
console.log(shop.address.city); // Karachi
console.log(shop.categories[0]); // FansLooping Through an Object
for...in goes through every key:
Example
const marks = { english: 78, maths: 91, urdu: 84 };
for (let subject in marks) {
console.log(subject + ": " + marks[subject]);
}english: 78 maths: 91 urdu: 84
Object.keys(marks) gives an array of the keys, and Object.values(marks) gives an array of the values.
Showing an object directly on a page gives [object Object]. Show its properties one by one, or use JSON.stringify(obj) to turn it into text.
Exercise
Exercise
Given const car = { make: "Suzuki", year: 2022 }; how do you read the year?
