Lesson 3 Review
In our last lesson, we learned how to write Functions to create reusable blocks of logic, and we learned how Variable Scope dictates where data is allowed to exist. Today, we scale up our data. Instead of storing one single value in a variable, we will store massive lists of data, and we will write code that automatically processes those lists.
Step 1: Arrays (Storing Multiple Values)
Until now, a variable could only hold one thing: let age = 25;. But what if you are building an e-commerce store and you need to store the names of 100 products? You cannot create 100 separate variables. You must use an Array.
An Array is a special variable that holds a list of items. You create an array using square brackets [ ], and you separate each item with a comma.
Zero-Based Indexing: The most important rule in programming is that computers do not start counting at 1. They start counting at 0. To grab a specific item out of an array, you ask for its "Index Number".
The JavaScript & HTML: Accessing Array Data
<p>The selected user is: <span id="display-user"></span></p>
/* JavaScript */
// Declare an array with 4 strings
let users = ["Alice", "Bob", "Charlie", "Diana"];
// Get the first item (Index 0 is Alice)
console.log(users[0]); // Outputs: Alice
// Get the third item (Index 2 is Charlie)
let targetUser = users[2];
// Inject it into the HTML
document.getElementById("display-user").innerHTML = targetUser;
The Output:
Step 2: Modifying Arrays (Methods)
Arrays are dynamic. You can add items to them or remove items from them while your program is running using built-in Array Methods.
push(): Adds a new item to the end of the array.pop(): Removes the last item from the end of the array.unshift(): Adds a new item to the beginning of the array.shift(): Removes the first item from the beginning of the array.length: A property (not a method) that tells you exactly how many items are currently inside the array.
The JavaScript: Adding to a Shopping Cart
// User clicks "Add to Cart" for a Hat
cart.push("Hat");
console.log(cart); // Outputs: ["Shoes", "Shirt", "Hat"]
// Check how many items are in the cart
let totalItems = cart.length;
console.log("Items in cart: " + totalItems); // Outputs: 3
Step 3: The 'for' Loop (Automating Tasks)
If you have an array with 10,000 users and you want to print all of their names, you cannot write console.log(users[0]) 10,000 times. You use a Loop.
A loop tells the browser: "Run this block of code over and over again until a specific condition is met." The most common loop is the for loop.
The for loop requires three mathematical statements inside its parentheses, separated by semicolons:
- Initialization: Create a starting counter variable (usually
let i = 0). - Condition: The rule that keeps the loop running (e.g., run as long as
i < 5). - Iteration: What happens to the counter after every cycle (usually
i++, which means "add 1 to i").
The JavaScript: A Basic Counter
// Repeat until i is no longer less than 5.
for (let i = 0; i < 5; i++) {
console.log("Cycle number: " + i);
}
Console Output:
> Cycle number: 1
> Cycle number: 2
> Cycle number: 3
> Cycle number: 4
Step 4: Looping Through Arrays to Build HTML
Here is where Front-End Engineering truly begins. We combine Arrays and Loops to automatically generate HTML code.
We set the loop condition to run exactly as many times as there are items in the array by using the array.length property. Inside the loop, we use the counter variable i to pull out the items one by one.
The HTML & JavaScript: Building a Dynamic List
<h3>Available Courses:</h3>
<ul id="course-list"></ul>
/* JavaScript */
let courses = ["HTML", "CSS", "JavaScript", "Python"];
let listElement = document.getElementById("course-list");
// Loop from 0 up to 3 (because courses.length is 4)
for (let i = 0; i < courses.length; i++) {
// += means "append". We are adding a new HTML
listElement.innerHTML += "<li>" + courses[i] + "</li>";
}
The Final HTML Output:
Available Courses:
- HTML
- CSS
- JavaScript
- Python
Step 5: Modern Array Methods (Higher-Order Functions)
While the standard for loop is great, modern JavaScript developers prefer using built-in Higher-Order Array Methods. These are cleaner, faster to write, and less prone to mathematical errors.
The forEach() Method
Instead of managing a counter variable i, forEach() automatically loops through every single item in the array and runs a function for you.
// Using an Arrow Function inside forEach
animals.forEach( (animal) => {
console.log("I have a " + animal);
});
The filter() Method
This is extremely powerful. filter() loops through an array, tests every item against a condition, and creates a brand new array containing only the items that passed the test.
// We only want passing grades (greater than 60)
let passingGrades = grades.filter( (score) => {
return score > 60;
});
console.log(passingGrades); // Outputs: [80, 95, 100]
Final Quiz: Test Your Engineering Logic
Click the buttons below to verify your knowledge of Arrays and Loops.
0 Comments