JavaScriptLesson 8 of 10Jump to practice

Objects

Group related values under names, and store lists of records as arrays of objects.

An array is a list in order. An object groups related values under names, called keys.

const student = {
  name: "Emma",
  age: 21,
  city: "Seattle",
  subjects: ["English", "Math"],
};

Each key: value pair is a property. Values can be anything: numbers, strings, arrays, even other objects.

Reading and changing properties

Working with an object
Open in editor
<script>
const student = { name: "Emma", age: 21, city: "Seattle" };

// Dot notation
console.log(student.name);

// Bracket notation: useful when the key is in a variable
const key = "city";
console.log(student[key]);

// Change and add properties
student.age = 22;
student.email = "rina@example.com";
console.log(student);

// A missing property is undefined
console.log(student.phone);
</script>
Result

Functions inside objects

A function stored in an object is called a method. Inside it, this means the object itself.

const counter = {
  count: 0,
  increase() {
    this.count++;
  },
};
counter.increase();
console.log(counter.count); // 1

Lists of records

Most real data is an array of objects: products, users, posts. Combine what you’ve learned to work with it.

A product list
Open in editor
<script>
const products = [
  { name: "Notebook", price: 3, inStock: true },
  { name: "Pen", price: 1, inStock: false },
  { name: "Backpack", price: 45, inStock: true },
];

for (const p of products) {
  console.log(p.name + ": $" + p.price);
}

const available = products.filter((p) => p.inStock);
console.log("In stock:", available.map((p) => p.name).join(", "));

const total = products.reduce((sum, p) => sum + p.price, 0);
console.log("Everything costs $" + total);
</script>
Result

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Print the user's city.

    const user = { name: "Emma", city: "Seattle" };
    console.log(user.);

  2. Exercise 2

    Read the property whose name is stored in the variable key.

    const key = "age";
    console.log(user);

  3. Exercise 3

    Separate the two properties correctly.

    const book = {
      title: "The Great Gatsby"
      author: "F. Scott Fitzgerald"
    };

Quiz: 3 questions

1. In { name: "Emma" }, what is name?
2. What does user.phone give if user has no phone property?
3. You need to store 50 students, each with a name and marks. What fits best?

Finish the practice to complete this lesson.