Storing Many Values in an Array

Five temperatures should not need five variables. An array stores many values in one ordered list. You write it with square brackets, with commas between the values:

const temps = [18, 21, 25, 19, 23];

console.log(temps);
console.log(temps.length);
console.log(temps[0]);
console.log(temps[4]);

Output:

[ 18, 21, 25, 19, 23 ]
5
18
23

Each value in an array is called an element. Each element has a position number called its index. The index starts at 0, not 1. So temps[0] is the first element and temps[4] is the fifth. .length gives the number of elements.

The index inside the brackets can also be a variable or a calculation:

<!-- continues -->
const i = 2;
console.log(temps[i]);
console.log(temps[temps.length - 1]);

Output:

25
23

The last element is at index temps.length - 1, because counting starts at 0. There is a shorter way to read from the end. The .at() method accepts a negative number and counts backwards: .at(-1) is the last element and .at(-2) is the one before it.

<!-- continues -->
console.log(temps.at(-1));
console.log(temps.at(-2));
console.log(temps[-1]);

Output:

23
19
undefined

Plain square brackets do not count from the end. temps[-1] gives undefined, so use .at() whenever you count from the end.

You can change an element by assigning a new value to its index:

<!-- continues -->
temps[1] = 22;
console.log(temps);

Output:

[ 18, 22, 25, 19, 23 ]

This works even though temps is a const. const only stops you from giving the name a new array, so temps = [1, 2] would be an error. The elements inside the array can still change. The last lesson of this section explains why.

What happens if you ask for an index that does not exist?

<!-- continues -->
console.log(temps[10]);
console.log(temps[10] + 1);

Output:

undefined
NaN

There is no error. JavaScript gives you undefined, the value that means "nothing was set here", and the program keeps running. The problem shows up later instead, like the NaN on the second line. So when you calculate an index, check it carefully. JavaScript will not warn you.

An array can hold any kind of value, even a mix of numbers and strings. In practice, keep one kind of thing in each array, such as only temperatures or only names. Your code stays simpler that way.

In the exercise, print the number of readings, the first and last reading, and the reading at an index from the input.