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
- Create an object
petwith three properties:name(a string),species(a string) andage(a number). - On a later line, increase the pet's
ageby 1. - Add a method
describethat returns a string in the formBiscuit is a dog, using the object's ownnameandspecies. - Print the result of calling
pet.describe().
petis an object with a stringname, a stringspeciesand a numberage- The age is increased by 1 after the object is created
describe()returnsname is a speciesdescribe()uses the object's own values, so it still works when they change- The description is printed
Lesson complete!
Next Lesson: Changing the Page