JavaScript: making your pages interactiveCreate account
Lesson 5 of 9

Arrays and objects

Real programs work with collections of things: a list of tasks, a cart full of products, a profile with a name, an email and an age. JavaScript has two tools for this. Arrays hold lists, and objects describe things.

Arrays: lists of values

An array is a list, written with square brackets and commas between the items:

javascript
const tasks = ['Buy milk', 'Learn JavaScript', 'Call grandma'];

Each item has a position, called an index. Here's the catch: counting starts at 0, not 1.

javascript
tasks[0];   // 'Buy milk'
tasks[1];   // 'Learn JavaScript'
tasks[2];   // 'Call grandma'

To find out how many items there are, use length:

javascript
tasks.length;   // 3

Since counting starts at 0, the last item is always at length - 1. That off by one detail catches everyone at least once.

Quick check

Given const colors = ['red', 'green', 'blue'], what is colors[1]?

Select one answer

Changing arrays

Arrays come with built-in methods for adding and removing items:

javascript
const tasks = ['Buy milk'];

tasks.push('Learn JavaScript');   // adds to the end
tasks.pop();                      // removes the last item
tasks.includes('Buy milk');       // true, the item is in the list

Wait, how can we change tasks if it's a const? Good question. const stops you from putting a new array in the variable, but you can still change what's inside the array. The box keeps the same array, the array just gets new contents.

Looping and transforming

You already know for...of. Arrays also have methods that take a function and run it for every item. These are where arrow functions really shine.

forEach runs a function for each item:

javascript
tasks.forEach((task) => {
  console.log(task);
});

map creates a new array by transforming every item:

javascript
const prices = [100, 250, 80];
const withTax = prices.map((price) => price * 1.25);
// [125, 312.5, 100]

filter creates a new array with only the items that pass a test:

javascript
const cheap = prices.filter((price) => price < 150);
// [100, 80]

map and filter don't change the original array. They give you a new one, which makes them safe to use without side effects.

Quick check

Which method creates a new array with only the items that match a condition?

Select one answer

Objects: describing things

An array is great for a list of similar things. But what about one thing with several properties, like a person? That's what objects are for:

javascript
const person = {
  name: 'Alex',
  age: 30,
  city: 'Göteborg',
  isStudent: true,
};

An object is written with curly braces and holds key and value pairs. name is a key and 'Alex' is its value. Each pair is separated by a comma.

You read values with a dot:

javascript
person.name;   // 'Alex'
person.age;    // 30

And you can change or add properties the same way:

javascript
person.age = 31;
person.email = 'alex@example.com';
Quick check

How do you read the city from const person = { name: 'Alex', city: 'Lund' }?

Select one answer

Arrays of objects

The real power comes from combining them. An array of objects is how most real data looks, from to-do lists to search results:

javascript
const tasks = [
  { text: 'Buy milk', done: true },
  { text: 'Learn JavaScript', done: false },
  { text: 'Call grandma', done: false },
];

const remaining = tasks.filter((task) => !task.done);
console.log(`You have ${remaining.length} tasks left`);

Read that filter out loud: "keep the tasks that are not done". That's the kind of code you'll write in this course's project.

JSON

You'll often see data written in a format called JSON, short for JavaScript Object Notation. It looks almost exactly like JavaScript objects and arrays, with one difference: keys must be in double quotes.

json
{ "text": "Buy milk", "done": true }

JSON is how data is sent between websites and servers, and how you'll save data in the browser later in this course. JavaScript has two built-in functions to convert between objects and JSON text:

javascript
const text = JSON.stringify(tasks);   // array to JSON text
const backAgain = JSON.parse(text);   // JSON text to array
Try it yourself

Practice with arrays and objects in script.js:

  1. Create an array of objects called courses, one for each course in this pathway, with a title and a finished boolean
  2. Use forEach to log each course title
  3. Use filter to get the finished courses and log how many there are
  4. Use map to create an array of just the titles, in uppercase
  5. Log JSON.stringify(courses) and look at what JSON looks like

Bonus: add a new course with push and log the length before and after.