Objects
🏠The everyday picture
A product's label in a shop: name, price, size, stock. Each detail has a heading and a value. An object is that label in code.
📘What it really is
- An object groups named values, called properties, describing one thing:
const product = {
id: "P001",
name: "Notebook",
price: 60,
inStock: true,
};
-
Read a property with a dot,
product.price, or with brackets and the name as text,product["price"](useful when the name is in a variable). -
Change or add:
product.price = 65;product.category = "Stationery";. - Remove:
delete product.category;. - Check if a property exists:
"price" in product. - Useful helpers:
Object.keys(product): the property names;Object.values(product): the values;-
Object.entries(product): pairs of name and value, handy in loops. -
Copying:
const copy = { ...product, price: 70 };makes a new object with one property changed. The original stays the same. -
Shorthand: if a variable has the same name as the property,
{ name, price }means{ name: name, price: price }. You'll see it everywhere in AI code.
🖱️Try it
Create an object for one product, with id, name, price, category and stock. Print each property using
Object.entries and a for...of loop:
for (const [key, value] of Object.entries(product)) {
console.log(`${key}: ${value}`);
}
Then make a copy with a new price and print both.
✅Quick check
You need a property whose name is stored in a variable field. How do you read it?
Show the answer
product[field]. The dot form would look for a property literally called "field".
const b = { ...a, price: 70 }. Does a.price change?
Show the answer
No. b is a new object; a is untouched.
