Complete solution (100% reference)
index.html- Main HTML pagescript.js- JavaScript logicstyles.css- Styling and layoutpackage.json- Dependenciessetup.sh- Setup scriptREADME.md- Instructions (below)💡 Download the ZIP, extract it, and follow the instructions below to get started!
This is the complete solution for Activity 07: Arrays. This guide provides instructors with detailed explanations, common student mistakes, discussion points, test cases, and assessment criteria.
Course: W2 Advanced JavaScript Foundations Activity: Activity 07 - Arrays Estimated Time: 60 minutes (for students) Difficulty: Beginner to Intermediate
By completing this activity, students will be able to:
✅ Understand array data structure and syntax ✅ Create and initialize arrays with multiple elements ✅ Access array elements using index notation ✅ Modify array elements by index assignment ✅ Use push() and pop() methods for array manipulation ✅ Iterate through arrays using forEach() method ✅ Apply conditional logic within array iterations ✅ Utilize index parameter for array modification ✅ Integrate JavaScript with HTML onclick events ✅ Transform data from one format to another
activity-07-arrays/
├── script.js # Complete solution with teaching comments
├── index.html # HTML with REPLACE button for Exercise 3
├── package.json # Dependencies for local dev server
├── setup.sh # Setup script for environment
└── README.md # This instructor guide
Goal: Create an array of zoo animals and display it in console
Solution:
var animals = ["gorilla", "parrot", "elephant", "giraffe", "tiger"];
console.log(animals);
Common Mistakes:
var animals = ("gorilla", "parrot");var animals = [gorilla, parrot];var animals = ["gorilla" "parrot"];var animals = ["gorilla", "parrot",];Discussion Points:
"gorilla" and gorilla? (String vs variable)Test Cases:
// Test 1: Array created correctly
console.log(animals); // Expected: ["gorilla", "parrot", "elephant", "giraffe", "tiger"]
// Test 2: Check length
console.log(animals.length); // Expected: 5
// Test 3: Access first element
console.log(animals[0]); // Expected: "gorilla"
Goal: Add and remove elements using push() and pop()
Solution:
var x = [100, 200, 300];
console.log(x); // [100, 200, 300]
x.push(400);
console.log(x); // [100, 200, 300, 400]
x.pop();
console.log(x); // [100, 200, 300]
Common Mistakes:
x.push = 400 (assignment, not method call)x.pop(400) (pop takes no parameters)x.pop() removes last, not firstDiscussion Points:
undefined)x.push(1, 2, 3))Test Cases:
// Test 1: Initial state
var x = [100, 200, 300];
console.log(x.length); // Expected: 3
// Test 2: After push
var newLength = x.push(400);
console.log(newLength); // Expected: 4
console.log(x); // Expected: [100, 200, 300, 400]
// Test 3: After pop
var removed = x.pop();
console.log(removed); // Expected: 400
console.log(x); // Expected: [100, 200, 300]
// Test 4: Pop empty array
var empty = [];
console.log(empty.pop()); // Expected: undefined
Real-World Analogy:
Goal: Create interactive seating chart with replacement functionality
Solution:
var seats = ["John", "Benjamin", "Hasan", "Lisa", "Tommy", "Kumar"];
var replaceIndex;
var newStudent;
function replace() {
replaceIndex = prompt("Which seat do you want to replace? (0-5)");
// Validation (BONUS)
if (replaceIndex === null) return;
replaceIndex = Number(replaceIndex);
if (isNaN(replaceIndex) || replaceIndex < 0 || replaceIndex >= seats.length) {
alert("Invalid seat number!");
return;
}
newStudent = prompt("Who is replacing this seat?");
if (newStudent === null || newStudent.trim() === "") {
alert("Invalid name!");
return;
}
// Replacement
var oldStudent = seats[replaceIndex];
seats[replaceIndex] = newStudent;
alert("Seat " + replaceIndex + " updated!\n" + oldStudent + " → " + newStudent);
console.log("Updated seats:", seats);
}
HTML Integration:
<button onclick="replace()">REPLACE SEAT</button>
Common Mistakes:
seats[replaceIndex] = newStudent where replaceIndex is a nameseats[replaceIndex] = "newStudent" instead of variableDiscussion Points:
array.length? (Number of elements)Test Cases:
// Test 1: Valid replacement
// Click REPLACE → Enter 2 → Enter "Winnie"
// Expected: seats[2] changes from "Hasan" to "Winnie"
console.log(seats); // ["John", "Benjamin", "Winnie", "Lisa", "Tommy", "Kumar"]
// Test 2: Edge case - first element
// Click REPLACE → Enter 0 → Enter "Alice"
console.log(seats[0]); // Expected: "Alice"
// Test 3: Edge case - last element
// Click REPLACE → Enter 5 → Enter "Bob"
console.log(seats[5]); // Expected: "Bob"
// Test 4: Invalid index (should show alert)
// Click REPLACE → Enter 100 → Should alert "Invalid seat number!"
// Test 5: Non-numeric input (should show alert)
// Click REPLACE → Enter "abc" → Should alert "Invalid seat number!"
Extension Challenge:
// Add swap functionality
function swap() {
var index1 = Number(prompt("First seat:"));
var index2 = Number(prompt("Second seat:"));
var temp = seats[index1];
seats[index1] = seats[index2];
seats[index2] = temp;
console.log("Swapped seats:", seats);
}
Goal: Create dairy products array and log each element
Solution:
var dairy = ["milk", "cheese", "yoghurt", "butter"];
dairy.forEach(function(item) {
console.log(item);
});
Expected Output:
milk
cheese
yoghurt
butter
Common Mistakes:
dairy.forEach (doesn't call method)dairy.forEach(item => console.log(item)) (ES6, teach traditional first)dairy.forEach(function(dairy) { ... }) (shadows variable)console.log(dairy[item]) (item IS the value)dairy.forEach(function(item) console.log(item))Discussion Points:
Comparison with for loop:
// Traditional for loop (manual)
for (var i = 0; i < dairy.length; i++) {
console.log(dairy[i]);
}
// forEach (automatic)
dairy.forEach(function(item) {
console.log(item);
});
Test Cases:
// Test 1: All items logged
dairy.forEach(function(item) {
console.log(item);
});
// Expected output: milk, cheese, yoghurt, butter (each on new line)
// Test 2: Count iterations
var count = 0;
dairy.forEach(function(item) {
count++;
});
console.log(count); // Expected: 4
Extension Challenge:
// Format with bullets
dairy.forEach(function(item) {
console.log("• " + item);
});
// Convert to uppercase
dairy.forEach(function(item) {
console.log(item.toUpperCase());
});
Goal: Implement charity funding system with conditional allocation
Solution:
var homes = [132000, 88000, 275000, 43000];
console.log("Initial funding:", homes);
homes.forEach(function(home) {
if (home < 90000) {
console.log(home + 50000); // Add support
} else {
console.log(home); // No change
}
});
Expected Output:
132000 (no change, already > 90000)
138000 (88000 + 50000)
275000 (no change, already > 90000)
93000 (43000 + 50000)
Common Mistakes:
home = home + 50000 (doesn't change array)home <= 90000 (includes 90000 exactly)home + 5000 instead of home + 50000console.log(home) in if blockDiscussion Points:
home = home + 50000 modify the array? (Pass by value for primitives)Test Cases:
// Test 1: Organizations below threshold get funding
var homes = [88000, 43000];
homes.forEach(function(home) {
if (home < 90000) {
console.log(home + 50000);
} else {
console.log(home);
}
});
// Expected: 138000, 93000
// Test 2: Organizations above threshold unchanged
var homes = [132000, 275000];
homes.forEach(function(home) {
if (home < 90000) {
console.log(home + 50000);
} else {
console.log(home);
}
});
// Expected: 132000, 275000
// Test 3: Boundary case - exactly 90000
var homes = [90000];
homes.forEach(function(home) {
if (home < 90000) {
console.log(home + 50000);
} else {
console.log(home);
}
});
// Expected: 90000 (no change, NOT < 90000)
Extension Challenge:
// Calculate total funding distributed
var totalAdded = 0;
homes.forEach(function(home) {
if (home < 90000) {
totalAdded += 50000;
console.log(home + 50000);
} else {
console.log(home);
}
});
console.log("Total additional funding: $" + totalAdded);
// Tiered funding system
homes.forEach(function(home) {
if (home < 50000) {
console.log(home + 75000); // Severe need: +$75k
} else if (home < 90000) {
console.log(home + 50000); // Moderate need: +$50k
} else {
console.log(home); // No additional funding
}
});
Goal: Create age verification system using forEach with index
Solution:
var queue = [12, 8, 25, 11, 38];
console.log("Original queue:", queue);
queue.forEach(function(age, index) {
if (age >= 12) {
queue[index] = true; // Can ride
} else {
queue[index] = false; // Too young
}
});
console.log("Updated queue:", queue);
Expected Output:
Original queue: [12, 8, 25, 11, 38]
Updated queue: [true, false, true, false, true]
Common Mistakes:
queue[age] = true (uses age value 12 as index!)queue.forEach(function(age) { queue[index] = true; }) (ReferenceError)queue.forEach(function(index, age) { ... }) (backwards!)queue[index] = "true" (should be boolean true)age = true (doesn't change array)Why Element as Index is Wrong:
var queue = [12, 8, 25];
// WRONG - using age (element value) as index
queue.forEach(function(age) {
queue[age] = true; // Sets queue[12]=true, queue[8]=true, queue[25]=true
});
console.log(queue); // [12, 8, 25, undefined × 9, true, undefined × 12, true]
// Creates sparse array with slots 12 and 25 set to true!
// CORRECT - using index parameter
queue.forEach(function(age, index) {
queue[index] = true; // Sets queue[0]=true, queue[1]=true, queue[2]=true
});
console.log(queue); // [true, true, true] ✅
Discussion Points:
>= 12 includes 12)Test Cases:
// Test 1: Basic transformation
var queue = [12, 8, 25, 11, 38];
queue.forEach(function(age, index) {
queue[index] = age >= 12;
});
console.log(queue); // Expected: [true, false, true, false, true]
// Test 2: Boundary case - exactly 12
var queue = [12];
queue.forEach(function(age, index) {
queue[index] = age >= 12;
});
console.log(queue[0]); // Expected: true (12 >= 12)
// Test 3: All eligible
var queue = [15, 20, 30];
queue.forEach(function(age, index) {
queue[index] = age >= 12;
});
console.log(queue); // Expected: [true, true, true]
// Test 4: None eligible
var queue = [5, 8, 10];
queue.forEach(function(age, index) {
queue[index] = age >= 12;
});
console.log(queue); // Expected: [false, false, false]
// Test 5: Count eligible
var queue = [12, 8, 25, 11, 38];
queue.forEach(function(age, index) {
queue[index] = age >= 12;
});
var canRide = queue.filter(function(eligible) { return eligible === true; }).length;
console.log(canRide); // Expected: 3
Extension Challenge:
// Keep original ages AND add eligibility
var ages = [12, 8, 25, 11, 38];
var eligible = [];
ages.forEach(function(age) {
eligible.push(age >= 12);
});
console.log("Ages:", ages); // [12, 8, 25, 11, 38]
console.log("Eligible:", eligible); // [true, false, true, false, true]
// Create age tiers
var queue = [12, 8, 25, 11, 38];
queue.forEach(function(age, index) {
if (age < 12) {
queue[index] = "child";
} else if (age < 18) {
queue[index] = "teen";
} else if (age < 65) {
queue[index] = "adult";
} else {
queue[index] = "senior";
}
});
console.log(queue); // ["teen", "child", "adult", "child", "adult"]
// Detailed report with years needed
var ages = [12, 8, 25, 11, 38];
ages.forEach(function(age, index) {
var status = age >= 12 ? "CAN RIDE" : "TOO YOUNG";
var diff = age >= 12 ? "" : " (needs " + (12 - age) + " more years)";
console.log("Person " + (index + 1) + ": " + age + " years → " + status + diff);
});
// Output:
// Person 1: 12 years → CAN RIDE
// Person 2: 8 years → TOO YOUNG (needs 4 more years)
// Person 3: 25 years → CAN RIDE
// Person 4: 11 years → TOO YOUNG (needs 1 more years)
// Person 5: 38 years → CAN RIDE
| Exercise | Points | Criteria |
|---|---|---|
| Exercise 1 | 10 | Correct array syntax with [], 5 string elements, console.log() displays array |
| Exercise 2 | 15 | Initial array with 3 elements, correct push() usage, correct pop() usage, console logs at each step |
| Exercise 3 | 25 | Seats array with 6 names, replace() function defined, two prompts for input, correct array[index] replacement, HTML button with onclick |
| Exercise 4 | 10 | Dairy array with 4 elements, correct forEach syntax, callback function logs each item |
| Exercise 5 | 20 | Homes array with 4 funding amounts, forEach with if/else, correct condition (< 90000), correct calculation (+ 50000), both branches log correctly |
| Exercise 6 | 20 | Queue array with 5 ages, logs original array, forEach with TWO parameters (age, index), correct condition (>= 12), modifies array with boolean true/false, logs updated array |
| BONUS | +5 | Input validation in Exercise 3 (null check, NaN check, range check, empty string check) |
Code Quality (embedded in each exercise):
Functionality (must work correctly):
Understanding (assessed through code correctness):
Day One: Exercises 1-2 (Array Basics)
Day 2: Exercise 3 (Index Access & HTML Integration)
Day 3: Exercise 4 (forEach Introduction)
Day 4: Exercise 5 (forEach + Conditionals)
Day 5: Exercise 6 (forEach with Index)
One. Zero-Based Indexing
2. Array Syntax Confusion
3. forEach Parameter Understanding
4. Array Modification vs Local Variables
5. HTML/JavaScript Integration
Demo 1: Array Inspector
var demo = ["a", "b", "c"];
console.table(demo); // Shows nice table in console
Demo 2: forEach Execution Trace
var nums = [10, 20, 30];
nums.forEach(function(num, index) {
console.log("Iteration:", index, "| Value:", num);
});
// Shows how forEach works step-by-step
Demo 3: Element vs Index Confusion
var ages = [12, 8];
console.log("WRONG WAY:");
ages.forEach(function(age) {
console.log("Setting ages[" + age + "] = true");
// Don't actually do it, just show what it would mean
});
console.log("\nCORRECT WAY:");
ages.forEach(function(age, index) {
console.log("Setting ages[" + index + "] = " + (age >= 12));
});
// Test Exercise 1
function testExercise1() {
var animals = ["gorilla", "parrot", "elephant", "giraffe", "tiger"];
console.assert(Array.isArray(animals), "Should be array");
console.assert(animals.length === 5, "Should have 5 elements");
console.assert(animals[0] === "gorilla", "First element should be 'gorilla'");
console.log("✅ Exercise 1 tests passed");
}
// Test Exercise 2
function testExercise2() {
var x = [100, 200, 300];
x.push(400);
console.assert(x.length === 4, "Length should be 4 after push");
console.assert(x[3] === 400, "Last element should be 400");
x.pop();
console.assert(x.length === 3, "Length should be 3 after pop");
console.assert(x[x.length - 1] === 300, "Last element should be 300");
console.log("✅ Exercise 2 tests passed");
}
// Test Exercise 6 (most complex)
function testExercise6() {
var queue = [12, 8, 25, 11, 38];
queue.forEach(function(age, index) {
queue[index] = age >= 12;
});
console.assert(queue[0] === true, "12 should be eligible");
console.assert(queue[1] === false, "8 should not be eligible");
console.assert(queue[2] === true, "25 should be eligible");
console.assert(queue[3] === false, "11 should not be eligible");
console.assert(queue[4] === true, "38 should be eligible");
console.log("✅ Exercise 6 tests passed");
}
// Run all tests
testExercise1();
testExercise2();
testExercise6();
Exercise 3 Interactive Testing:
var cart = ["apple", "banana", "orange"];
var prices = [1.50, 0.75, 2.00];
function addItem(item, price) {
cart.push(item);
prices.push(price);
console.log("Added:", item, "($" + price + ")");
}
function removeItem() {
var item = cart.pop();
var price = prices.pop();
console.log("Removed:", item, "($" + price + ")");
}
function calculateTotal() {
var total = 0;
prices.forEach(function(price) {
total += price;
});
console.log("Total: $" + total.toFixed(2));
}
addItem("grape", 3.00);
calculateTotal(); // $7.25
removeItem();
calculateTotal(); // $4.25
var students = ["Alice", "Bob", "Charlie", "David"];
var grades = [85, 92, 78, 95];
function calculateAverage() {
var sum = 0;
grades.forEach(function(grade) {
sum += grade;
});
return sum / grades.length;
}
function countPassFail() {
var pass = 0;
var fail = 0;
grades.forEach(function(grade) {
if (grade >= 70) {
pass++;
} else {
fail++;
}
});
console.log("Pass:", pass, "Fail:", fail);
}
function findTopStudent() {
var highest = 0;
var topStudent = "";
grades.forEach(function(grade, index) {
if (grade > highest) {
highest = grade;
topStudent = students[index];
}
});
console.log("Top student:", topStudent, "with grade:", highest);
}
console.log("Class average:", calculateAverage());
countPassFail();
findTopStudent();
var todos = ["Buy groceries", "Finish homework", "Call mom"];
var completed = [false, false, false];
function addTodo(task) {
todos.push(task);
completed.push(false);
console.log("Added:", task);
}
function completeTodo(index) {
if (index >= 0 && index < todos.length) {
completed[index] = true;
console.log("Completed:", todos[index]);
}
}
function displayTodos() {
console.log("\nTodo List:");
todos.forEach(function(task, index) {
var status = completed[index] ? "✓" : "○";
console.log(status, (index + 1) + ".", task);
});
}
displayTodos();
completeTodo(1);
displayTodos();
addTodo("Clean room");
displayTodos();
Part One: Basic Operations
Part 2: Array Methods
Code Quality
Functionality
If students encounter issues:
Common error messages and fixes:
Uncaught ReferenceError: X is not defined -> Variable not declared or spelled wrongUncaught TypeError: X is not a function -> Trying to call non-function or wrong method nameUncaught SyntaxError: Unexpected token -> Missing bracket, comma, or quoteStudents should verify they have:
Bonus completion:
Version: 1.0 Last Updated: 2025-10-10 Author: Telebort Engineering Course: W2 Advanced JavaScript Foundations