Lesson 1.11: Arrays
An array keeps several values in order, in a single variable.
The idea
Instead of one variable per fruit, one array with all of them. It goes in square brackets, with the values separated by commas:
const fruits = ["apple", "pear", "grape"];
Positions start at 0
Each value has a position, and the first one is 0:
console.log(fruits[0]);
console.log(fruits[2]);
console.log(fruits.length);
apple
grape
3
fruits.lengthtells you how many values there are.- The last position is
fruits.length - 1. - A position that doesn't exist gives
undefined.
Changing the array
fruits.push("kiwi");
fruits[0] = "strawberry";
console.log(fruits);
(4) ['strawberry', 'pear', 'grape', 'kiwi']
- The console puts the number of values in front:
(4). push()adds to the end.fruits[0] = …changes the value at that position.
With const the array can change inside. What can't happen is fruits becoming a different array.
Going through it
for … of visits each value, in order:
for (const fruit of fruits) {
console.log(fruit);
}
Try it
With the array const marks = [7, 4, 9, 6];, work out and write the average.
Show the solution
const marks = [7, 4, 9, 6];
let sum = 0;
for (const mark of marks) {
sum = sum + mark;
}
console.log(sum / marks.length);
6.5
Summary
- An array keeps several values in order:
[1, 2, 3]. - Positions start at 0;
lengthsays how many there are. push()adds;for … ofgoes through it.