JavaScript Basics · Lesson 10 of 13

Objects

An array is a list of values in order. An object is a group of values with names. It describes one thing:

const book = {
  title: "Dune",
  author: "Frank Herbert",
  pages: 612,
};

Each line inside the braces is a property: a name (the key), a colon and a value. Properties are separated by commas.

Reading and changing properties

Use a dot and the property name:

console.log(book.title);    // "Dune"
book.pages = 620;           // change a value
book.read = true;           // add a new property

Asking for a property that does not exist gives the special value undefined.

Methods

A property can hold a function. Then it is called a method, and inside it the word this refers to the object itself:

const dog = {
  name: "Rex",
  speak() {
    return `${this.name} says woof`;
  },
};
console.log(dog.speak());   // "Rex says woof"

That is what console.log is: an object called console with a method called log.

Arrays of objects

Real programs are full of arrays of objects: a list of products, messages or users. The array methods from the last lesson work on them too:

const books = [
  { title: "Dune", pages: 612 },
  { title: "Emma", pages: 474 },
];
const titles = books.map((b) => b.title);   // ["Dune", "Emma"]

Your Task

  1. Create an object pet with three properties: name (a string), species (a string) and age (a number).
  2. On a later line, increase the pet's age by 1.
  3. Add a method describe that returns a string in the form Biscuit is a dog, using the object's own name and species.
  4. Print the result of calling pet.describe().
  • pet is an object with a string name, a string species and a number age
  • The age is increased by 1 after the object is created
  • describe() returns name is a species
  • describe() uses the object's own values, so it still works when they change
  • The description is printed