Skip to content
Programming contents

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:

JavaScript
const fruits = ["apple", "pear", "grape"];

Positions start at 0

Each value has a position, and the first one is 0:

JavaScript
console.log(fruits[0]);
console.log(fruits[2]);
console.log(fruits.length);
Console
apple
grape
3
  • fruits.length tells you how many values there are.
  • The last position is fruits.length - 1.
  • A position that doesn't exist gives undefined.

Changing the array

JavaScript
fruits.push("kiwi");
fruits[0] = "strawberry";
console.log(fruits);
Console
(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:

JavaScript
for (const fruit of fruits) {
  console.log(fruit);
}

Try it

Exercise

With the array const marks = [7, 4, 9, 6];, work out and write the average.

Show the solution
JavaScript
const marks = [7, 4, 9, 6];
let sum = 0;

for (const mark of marks) {
  sum = sum + mark;
}

console.log(sum / marks.length);
Console
6.5

Summary

  • An array keeps several values in order: [1, 2, 3].
  • Positions start at 0; length says how many there are.
  • push() adds; for … of goes through it.