Loops, and where your data lives

INPUT · Slides

Holding values by name with an object

01 / 04

Remembering by number is hard work

Hold the details of a book in an array and you get something like ["Sky Book", 800, 120].

But you cannot read that unless you remember that number 1 is the price and number 2 is the page count. Numbers are good at saying "which one along"; they will not tell you what a value is.

02 / 04

An object holds by name

An object is what lets you hold each value under a name. Inside { } you line up name: value pairs, separated by ,.

Each of those name and value pairs is called a property. To take one out you just write object.name.

const book = { title: "Sky Book", price: 800 };console.log(book.title);console.log(book.price);

Result

Sky Book
800

03 / 04

What comes out is an ordinary value

book.price is like something taken out of an array: you can treat it as just a number.

It works in maths and it drops into a template literal.

const item = { name: "bread", price: 160, count: 3 };console.log(`${item.count} ${item.name} for ${item.price * item.count} yen`);

Result

3 bread for 480 yen

04 / 04

Choosing between an array and an object

The two have different jobs.

  • an array … holds things of the same kind in a row. "a list of fruit", "a list of scores"
  • an object … holds the various details about one thing. "the title, price and page count of one book"

If you are unsure, ask whether the order means anything. If it does, array; if not, object.

const fruits = ["apple", "orange"];const user = { name: "Yui", age: 12 };console.log(fruits[0]);console.log(user.name);

Result

apple
Yui