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
Task 1, not checked yet. Make a constant
secondthat holds the second item offruits.Task 2, not checked yet. Add the text
'date'to the end offruits. Use thepushmethod.Task 3, not checked yet. Make a constant
countthat holds the number of items infruits. Write it after thepushline.Task 4, not checked yet. Use a
for...ofloop to print each fruit in capital letters, one on each line.Task 5, not checked yet. Make a constant
listthat joins the items offruitsinto one text, with' and 'between the items. Use thejoinmethod.
Task 1 of 5
Make a constant second that holds the second item of fruits.