Arrays and Objects
An array is an ordered list of values in square brackets. Items are counted from 0. length tells you how many there are.
An object groups related values under names, called properties, inside curly braces. Read a property with a dot: product.price.
Almost all real data is arrays and objects. A shop has an array of products; each product is an object with a name, price and stock. A user is an object; their orders are an array of objects. When websites send data to each other (JSON), it's in exactly this shape.
Arrays answer "which items, in what order?". Objects answer "what are the details of this one thing?". You'll often combine them: products[0].price means "the price of the first product".
<!DOCTYPE html>
<html>
<body>
<ul id="list"></ul>
<p id="sum"></p>
<script>
const products = [
{ name: "Pen", price: 20 },
{ name: "Notebook", price: 60 },
{ name: "School bag", price: 799 }
];
const list = document.getElementById("list");
products.forEach(function (p) {
const li = document.createElement("li");
li.textContent = p.name + " - Rs " + p.price;
list.appendChild(li);
});
const cheap = products.filter(p => p.price < 100);
const total = products.reduce((sum, p) => sum + p.price, 0);
document.getElementById("sum").textContent =
products.length + " items, total Rs " + total + ", " + cheap.length + " under Rs 100";
</script>
</body>
</html>▶ Try it yourselfpush()adds an item to the end of an array.forEach()runs a function for every item.filter()keeps only the items that pass a test.map()turns each item into something new.
These array methods are used all the time in modern JavaScript, React and Angular. They let you describe what you want ("keep the cheap products", "get their names") instead of writing loops by hand, which makes code shorter and less error-prone. filter and map return new arrays and leave the original unchanged.
- Arrays: ordered lists, counted from 0, with
length. - Objects: named properties, read with a dot.
push,forEach,filter,mapare everyday tools.
