VCF

Unit 5 · Data and algorithms

Array vs object: which one to use

Use an array for a list where position matters: a queue, a ranking, steps in order. Use an object for one record whose facts have names: a contact with a name, a phone and an email.

The mix-up

What people often think

“A contact is a list of things about a person, so it is an array.”

What the tutor says

In an array you would have to remember that position 1 is the phone. An object lets you ask for contact.phone by name.

Which is easier to read later: friend[2] or friend.email?

How it works

Storing a contact as an array means remembering that position 1 is the phone. friend.email is easier to read later than friend[2].

Objects have no positions, only keys. The key is the label you look up by (phone); the value is what you get back (the number). For a top 10, the position is the meaning, so an array already numbers every song for you.

An example

What worksJavaScript
const topSongs = ["Song A", "Song B", "Song C"];   // order matters
const contact  = { name: "Priya", phone: "555-0142" }; // named facts

topSongs[0];     // number one
contact.phone;   // "555-0142"
Lists by position, records by name.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “A top 10 needs names for each place, so it is an object.”

    The position is the meaning here. An array already numbers every song in order, so songs[0] is number one.

  • “Objects are numbered like arrays.”

    An object has no positions, only names. Ask for the fact by its key: contact.phone.

  • “The phone number is the key, because it is the thing you want.”

    The key is the label you look things up by: phone. The value is what you get back: the number itself.

Practise it with a tutor watching

Arrays and objects

Store a list in an array, a record in an object, and read any item back out.

20 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.