Lesson 6 of 10

Working With Data

Lesson 6: Arrays and Objects

Arrays store lists. Objects store details. Most real projects use both together.

Learning Goals

Real Example: Restaurant Menu

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
Tip: Run node lesson6.js in your terminal to see the output. Try changing the values and see what happens.

Practice

  1. Create an array with 4 fruits.
  2. Create an object with your profile data.
  3. Print one array item and one object value.

Homework

Create an array of 3 students. Create one object for each student with name and score.

Answer Guide
let students = [
  { name: "Asha", score: 75 },
  { name: "Brian", score: 62 },
  { name: "Cynthia", score: 84 }
];

console.log(students[0].name);
console.log(students[2].score);
← Previous Lesson Next Lesson →