Lesson 10 of 15

Arrays

Arrays

An array is an ordered list of values. Create one with square brackets:

const fruits = ["apple", "banana", "cherry"];

Accessing Elements

Arrays are zero-indexed — the first element is at index 0:

console.log(fruits[0]);  // apple
console.log(fruits[1]);  // banana
console.log(fruits[2]);  // cherry

Length

console.log(fruits.length);  // 3

Modifying Arrays

push adds to the end, pop removes from the end:

fruits.push("date");
console.log(fruits.length);  // 4
console.log(fruits[3]);      // date

const last = fruits.pop();
console.log(last);            // date
console.log(fruits.length);  // 3

Iterating

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

Your Task

Create an array primes containing [2, 3, 5, 7, 11]. Print the first element, the last element, and the length.

JavaScript loading...
Loading...
Click "Run" to execute your code.