1. What do arrays allow us to do?
Arrays allow us to access each of its elements by using the array name and the index of each element, which is written in square brackets. Arrays are very useful in combination with for loops, if you want to execute the same code on each element of the array. You can access the number of elements in the array by using the length attribute, for example myArray.length
.
Arrays can also be passed as an argument for functions. For example if you want to calculate the average of all values in an array of numbers. This way you can pass an arbitrary number of arguments to a function using the ...
statement before your array name in your function call. If you try to find the highest value in an array of numbers you simply use Math.max(...numbers);
to access this value!
2. What index should you use in order to access the first element in an array?
The first index of an array is always zero. You can access this element by using the name of the array followed by a 0 in square brackets, for example myArray[0]. Because the counting starts at 0 and we have myArray.length
elements in the array, the highest index of this array is myArray.length - 1
.