JavaScript

Lesson 7 of 11

Lesson ยท 10 min

Arrays

Many values in one name

An array is an ordered list of values. You write it with square brackets, and you separate the items with commas.

const colors = ['red', 'green', 'blue'];
const scores = [10, 7, 9];

An array can hold any kind of value, and the items do not have to be of the same kind.

Reading items

Each item has a position, called an index. The first index is 0.

console.log(colors[0]);     // red
console.log(colors[2]);     // blue
console.log(colors.length); // 3

The index of the last item is always length - 1.

Changing an array

Code What it does
colors.push('pink') adds an item to the end
colors.pop() removes the last item and gives it to you
colors.includes('red') is true when the item is in the array
colors.indexOf('blue') gives the index of the item, or -1
colors.join(', ') joins the items into one text

A const array can still change. The word const only means that the name always points to the same array.

Going through an array

The for...of loop gives you each item, one after the other. You do not need a counter.

for (const color of colors) {
  console.log(color);
}

Your turn

The array fruits is already in the editor. Write your code under it. Some tasks depend on the tasks before them.

Tasks

5 to do

  1. Task 1, not checked yet. Make a constant second that holds the second item of fruits.

  2. Task 2, not checked yet. Add the text 'date' to the end of fruits. Use the push method.

  3. Task 3, not checked yet. Make a constant count that holds the number of items in fruits. Write it after the push line.

  4. Task 4, not checked yet. Use a for...of loop to print each fruit in capital letters, one on each line.

  5. Task 5, not checked yet. Make a constant list that joins the items of fruits into one text, with ' and ' between the items. Use the join method.

Task 1 of 5

Make a constant second that holds the second item of fruits.

All tasks

main.js

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.