Learning Goals
- Create arrays and objects.
- Read values from arrays and objects.
- Update values in arrays and objects.
Working With Data
Arrays store lists. Objects store details. Most real projects use both together.
Imagine you are running a small restaurant. You want to keep a list of what you sell. In JavaScript, you would write:
// This is a list (array) of menu items
let menuItems = ["Rolex", "Matoke", "Tilapia"];
Now, let's say a customer makes an order. We want to store the details of that order. For that, we use an object:
// This is an object with details about the order
let order = {
item: "Rolex",
quantity: 2,
paid: false
};
When we write let order = { item: "Rolex", quantity: 2, paid: false };, we mean: we are creating one object named order with related details inside it.
We can change the order, for example, when the customer pays:
order.paid = true;
And we can add new items to our menu:
menuItems.push("Passion Juice");
Let's see what happens if we print these out:
console.log(menuItems[0]); // Rolex
console.log(order.item); // Rolex
console.log(order); // Shows all order details
node lesson6.js in your terminal to see the output. Try changing the values and see what happens.Create an array of 3 students. Create one object for each student with name and score.
let students = [
{ name: "Asha", score: 75 },
{ name: "Brian", score: 62 },
{ name: "Cynthia", score: 84 }
];
console.log(students[0].name);
console.log(students[2].score);