Curriculum / Fundamentals / Lesson 09

Arrays in JavaScript

Creating, looping, and the array methods you'll use constantly.

9 of 30
beginner 📖 7 min read 🎯 4 questions

What is an Array?

An array is a special variable that holds multiple values in an ordered list. You can store numbers, strings, objects, or even other arrays.

💡 Real-world analogy Think of an array like a numbered list. Each item has a position (index) starting from 0, just like items on a grocery list.

Creating Arrays

// Array literal (preferred)
let fruits = ["apple", "banana", "orange"];

// Using the Array constructor
let numbers = new Array(1, 2, 3, 4, 5);

// Empty array
let empty = [];

Accessing Array Elements

Use square brackets with the index (starting from 0).

let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "orange"
console.log(fruits.length); // 3

Common Array Methods

Looping Through Arrays

let fruits = ["apple", "banana", "orange"];

// Traditional for loop
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// for...of loop (cleaner)
for (let fruit of fruits) {
  console.log(fruit);
}

Common Mistakes

Quick Quiz

1. What is the index of the last element in an array of length 5?

2. Which method adds an item to the end of an array?

3. What does fruits[0] give you?

Summary

Back to curriculum