JavaScript – Making Webpages Interactive!
intermediate30 XP

Loops & Arrays – Working with Lists of Data!

Loop through arrays to display lists, build galleries and process data — the foundation of dynamic websites!

Loops & Arrays — Processing Data Like a Pro! 🔄

Almost every website works with lists of data — YouTube's video list, Spotify's playlist, a shop's products. Loops let you process these lists automatically!

Arrays — Storing Lists of Data

JavaScript
// An array is a list in square brackets
let games = ["Minecraft", "Roblox", "Fortnite", "Among Us"];
let scores = [95, 87, 100, 76, 89];
let mixed = ["Alex", 13, true, null];  // can mix types!

// Access items by position (starts at 0!)
console.log(games[0]);    // "Minecraft" (first item)
console.log(games[2]);    // "Fortnite" (third item)
console.log(games.length); // 4 (how many items)

Array Methods

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

fruits.push("mango");          // add to end
fruits.unshift("strawberry");  // add to start
fruits.pop();                  // remove last item
fruits.includes("banana");     // true (is it in there?)
fruits.indexOf("apple");       // 1 (what position?)

// Join all items into a string
console.log(fruits.join(", "));  // "strawberry, apple, banana"

For Loop — Do something N times

JavaScript
for (let i = 0; i < 5; i++) {
  console.log("Counting: " + i);
}
// Prints: 0, 1, 2, 3, 4

For...of Loop — Loop through an array

JavaScript
let games = ["Minecraft", "Roblox", "Fortnite"];

for (let game of games) {
  console.log("🎮 " + game);
}
// Prints:
// 🎮 Minecraft
// 🎮 Roblox  
// 🎮 Fortnite

forEach — Array's built-in loop

JavaScript
games.forEach(function(game, index) {
  console.log((index + 1) + ". " + game);
});
// Prints:
// 1. Minecraft
// 2. Roblox
// 3. Fortnite

While Loop — Keep going until condition is false

JavaScript
let lives = 3;

while (lives > 0) {
  console.log("Lives remaining: " + lives);
  lives--;    // reduce by 1
}
console.log("Game over! 😢");

🌟 Generate a Games List in HTML!

JavaScript
const games = [
  { name: "Minecraft", emoji: "⛏️" },
  { name: "Roblox", emoji: "🎮" },
  { name: "Fortnite", emoji: "🏆" }
];

let html = "<ul>";

games.forEach(game => {
  html += `<li>${game.emoji} ${game.name}</li>`;
});

html += "</ul>";

document.getElementById("game-list").innerHTML = html;

This is how Netflix automatically generates movie cards — it loops through an array of movies and creates HTML for each one! 🎬

Quick check

01/3

What is the index of the FIRST item in a JavaScript array?