Creating and accessing arrays
Learn to create array literals and access elements by index.
What is an array?
An array is an ordered list of values. You write values inside square brackets [] separated by commas.
For example const fruits = ["apple", "pear", "banana"]; stores three strings in order. Arrays can hold numbers, strings, booleans or even other arrays.
Each element has an index. The first element is at index 0, the second at index 1, and so on.
length and zero-based indexing
The number of elements in an array is given by the length property. For example fruits.length returns three.
Arrays are zero-indexed. The first element is fruits[0], the second is fruits[1]. The last element has index length - 1.
So in a three-element array the last element is fruits[2], not fruits[3]. Accessing fruits[3] returns undefined; it is not an error, just an undefined value.
Exercise Create and print from the colors array
Create an array named colors with at least three color strings. Then print the second element (index 1) with console.log.
Show example solution
Write at least three strings in square brackets, then put colors[1] inside console.log.
Example solution:
const colors = ["red", "blue", "green"];
console.log(colors[1]);
Test yourself
-
Which expression accesses the value 'banana' in the <code>fruits</code> array?
const fruits = ["apple", "pear", "banana", "cherry"];- fruits[3]
- fruits[2]
- fruits(2)
- fruits.2
Show answer
fruits[2] — Correct. 'banana' is the third element, so its index is 2.
-
Create the numbers array
const numbers = ____; console.log(numbers[0]);Show answer
const numbers = [10, 20, 30]; console.log(numbers[0]); -
Match each expression with its value for <code>fruits = ["apple", "pear", "banana"]</code>
- fruits[0]
- apple
- fruits[1]
- pear
- fruits[2]
- banana
- fruits.length
- 3