JavaScript Loops and Arrays | Lecture 33 - BLOG PK
Skip to content

JavaScript Loops and Arrays | Lecture 33

JavaScript Loops and Arrays

Let’s begin with Lecture 33 of the HTML5 & CSS3 series. JavaScript Loops and Arrays – Working with Lists and Repetition. This lecture is for absolute beginners; even kids can follow along and understand.

🎯 Objective:

By the end of this lecture, you will:

  • Understand what arrays are and how to use them
  • Know how to repeat tasks using loops (for, while, forEach)
  • Be able to create dynamic content like lists, quizzes, and counters
  • Use arrays to store and show multiple values
  • Make your JavaScript code more powerful and efficient!

πŸ“¦ What Are Arrays?

An array is a list of values stored in one variable.

Think of it like this:

If variables are boxes that hold one item, then arrays are backpacks that can hold many items!

Example:
let colors = ["red", "green", "blue"];

You can access items by their index β€” which starts at 0:

console.log(colors[0]); // red
console.log(colors[1]); // green

Arrays can hold any data types:

let mix = ["apple", 5, true, "hello"];

πŸ” What Are Loops?

Loops let you run the same code over and over β€” perfect for working with arrays or repeating actions.

Think of it like this:

If your code was a song, loops are the chorus β€” it plays again and again without writing it all over.

πŸ”„ Types of Loops
LOOPUSE WHEN
forYou know how many times to repeat
whileRepeat while a condition is true
forEachRun a function on each array item
πŸ’» Try This: Display a List of Skills from an Array

Let’s update your portfolio page to display skills using a JavaScript array and loop.

Step 1: Open portfolio.html

Or create a new file named:

skills-list.html

Step 2: Add HTML

<h2>Skills</h2>
<ul id="skillsList"></ul>
Step 3: Add JavaScript

Before </body>:

<script>
    // Create an array of skills
    let skills = ["HTML", "CSS", "JavaScript", "Problem Solving", "Creativity"];

    // Loop through the array and add each skill to the page
    let list = document.getElementById("skillsList");

    for (let i = 0; i < skills.length; i++) {
        let li = document.createElement("li");
        li.textContent = skills[i];
        list.appendChild(li);
    }
</script>

πŸŽ‰ Now your skills appear dynamically using JavaScript β€” no hard-coded HTML needed!

πŸ’‘ Bonus: Build a Simple Quiz with a Loop

Let’s make a quiz where users guess favorite things.

Add HTML:
<h2>Guess My Favorite Things</h2>
<input type="text" id="guessInput">
<button onclick="checkGuess()">Submit Guess</button>

<p id="quizResult"></p>
Add JavaScript:
<script>
    // My favorite things
    let favorites = ["blue", "pizza", "coding", "space"];

    function checkGuess() {
        let userGuess = document.getElementById("guessInput").value.toLowerCase();
        let found = false;

        // Loop through the array to find match
        for (let i = 0; i < favorites.length; i++) {
            if (userGuess === favorites[i]) {
                found = true;
                break;
            }
        }

        let result = document.getElementById("quizResult");

        if (found) {
            result.textContent = "βœ… Yes! That's one of my favorites!";
        } else {
            result.textContent = "❌ Nope, try again!";
        }
    }
</script>

Now users can guess your favorite things and get instant feedback!

πŸ’‘ Bonus: Counter with While Loop

Let’s build a counter that increases every time a button is clicked.

Add HTML:
<h2>Counter</h2>
<p id="counterDisplay">0</p>
<button onclick="increaseCounter()">Click Me!</button>
Add JavaScript:
<script>
    let count = 0;

    function increaseCounter() {
        count++;
        document.getElementById("counterDisplay").textContent = count;
    }
</script>

Each click increases the number β€” simple and fun!

JavaScript Loops and Arrays
A kid typing into a computer screen drawing a long line of balloons labeled Item
πŸ’‘ Bonus: Dynamic List Builder

Let’s let users add items to a list using an input and a button.

Add HTML:
<h2>Add to Your List</h2>
<input type="text" id="itemInput">
<button onclick="addItem()">Add Item</button>
<ul id="dynamicList"></ul>
Add JavaScript:
<script>
    function addItem() {
        let input = document.getElementById("itemInput");
        let value = input.value;

        if (value.trim() !== "") {
            let ul = document.getElementById("dynamicList");

            let li = document.createElement("li");
            li.textContent = value;

            ul.appendChild(li);

            // Clear input
            input.value = "";
        } else {
            alert("Please enter something!");
        }
    }
</script>

Now users can build their own list live!

πŸ§ͺ Try It Yourself!

  1. Create a to-do list app where users can add and clear tasks.
  2. Make a random quote generator using an array of quotes and Math.random().
  3. Use forEach to style each skill tag differently when hovered.
  4. Build a number guessing game with hints like β€œToo high!” or β€œToo low!”
βœ… Summary of What You Learned Today
CONCEPTCODE EXAMPLE
Arraylet fruits = ["apple", "banana", "orange"];
Access Itemfruits[1] β†’ "banana"
Loop (for)for (let i = 0; i < array.length; i++) { ... }
Loop (forEach)array.forEach(item => { ... });
Dynamic ContentCreate elements and add them to the page using JavaScript

πŸš€ Next Lecture Preview:

In Lecture 34 , we’ll learn how to work with the Document Object Model (DOM) β€” so you can select , create , and modify HTML elements directly using JavaScript β€” making your website truly interactive and alive!

Stay Updated

If you found this information useful, don’t forget to bookmark this page and Share.

HTML5 and CSS3 Compleate Series

Najeeb Alam

Najeeb Alam

Technical writer specializes in developer, Blogging and Online Journalism. I have been working in this field for the last 20 years.