Week 7: Array Methods and Iterators
To Do This Week:
Assignments:
- Slider/Menu Site (5%) — mostly in class, due end of the week — no AI-generated code (Due 10/14)
You'll receive a provided HTML/CSS structure containing an image slider and an animated navigation menu. Your task is to write the JavaScript that makes the interface work — and to be able to explain every part of it.
Read (Optional!): Chapters from Eloquent JavaScript:
- Handling Events (review)
- The Document Object Model (review)
Upcoming Assignments
- JavaScript Codecademy #2 (10%) (Due Week 8 — 10/14)
Student Projects:
Challenge: Volume Knob
- describe what should happen in plain English.
- write numbered logic steps as a comment.
- turn one step at a time into JavaScript. Test after each step.
console.log()your variables so you can see what the program is thinking.
Two buttons turn a "volume" up and down between 0 and 10. The number shows on the page. At 0 the label says Muted; at 8 or higher it says Loud! and turns red. The volume can never go below 0 or above 10.
Copy starter HTML into a new .html file and open it in the browser with the Console open.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; text-align: center; padding: 40px; }
#level { font-size: 80px; margin: 10px; }
.loud { color: red; }
button { font-size: 24px; padding: 10px 20px; }
</style>
</head>
<body>
<h1>Volume</h1>
<p id="level">5</p>
<p id="label"></p>
<button id="down">−</button>
<button id="up">+</button>
<script>
/*
1. Store the volume in a variable (start at 5).
2. Select the level text, the label, and both buttons.
3. Write updateDisplay(): put the volume on the page;
if 0 → "Muted"; if 8 or more → "Loud!" + add class "loud";
otherwise → clear the label and remove "loud".
4. Write volumeUp(): if volume is less than 10, add 1. Then updateDisplay().
5. Write volumeDown(): if volume is more than 0, subtract 1. Then updateDisplay().
6. Add click listeners to the buttons.
7. Call updateDisplay() once so the page starts correct.
*/
</script>
</body>
</html>
let volume = 5;
const level = document.querySelector("#level");
const label = document.querySelector("#label");
const upBtn = document.querySelector("#up");
const downBtn = document.querySelector("#down");
function updateDisplay() {
level.textContent = volume;
console.log("volume is", volume);
if (volume === 0) {
label.textContent = "Muted";
level.classList.remove("loud");
} else if (volume >= 8) {
label.textContent = "Loud!";
level.classList.add("loud");
} else {
label.textContent = "";
level.classList.remove("loud");
}
}
function volumeUp() {
if (volume < 10) {
volume++;
}
updateDisplay();
}
function volumeDown() {
if (volume > 0) {
volume--;
}
updateDisplay();
}
upBtn.addEventListener("click", volumeUp);
downBtn.addEventListener("click", volumeDown);
updateDisplay();
Challenge: Color Buttons
Goal: Make the color of the button you click become the color of the display box.
There are many ways to solve this. You could give every button its own id and write a separate event listener for each one. That works, but it repeats the same kind of code over and over.
Instead, we are going to look for the repeated pattern and use a loop to work through all of the buttons.
Think Through the Problem First
Before writing JavaScript syntax, describe what the program needs to do in normal human language.
- Find the display box.
- Find all of the color buttons.
- Go through the buttons one at a time.
- Make each button listen for a click.
- When a button is clicked, find out what color that button represents.
- Send that color to a function.*
- Have the function change the display box to that color.
Translate the Human Steps into JavaScript Logic
Now describe the same process using JavaScript ideas, but do not worry about exact syntax yet.
- Create a variable that refers to the display element.
- Create a variable that contains all of the buttons.
- Loop through the collection of buttons.
- For each button, attach a click event listener.
- Inside the event listener, get the color from the current button.
- Call a function and pass the color into it as a parameter.
- Inside the function, use the parameter to change the display element's CSS.
*Note: You do not technically need a separate function to change the display color. The DOM changes could happen directly inside the click event listener. In this challenge, we will move those changes into a separate function so we can practice functions with parameters and see how a value can be passed from an event into another part of the program.
When JavaScript selects several elements with querySelectorAll(), it gives you a collection that works much like an array. The first element is at index 0, the second is at index 1, and so on.
buttons[0]
buttons[1]
buttons[2]
buttons[3]
This is why a for loop is useful: the variable i can act as both a counting number and the index of the current button.
After we solve the problem with a for loop, we can ask whether we actually need the counting number. If all we want is to do the same thing to every button, forEach() gives us the current button directly.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: sans-serif;
text-align: center;
padding: 40px;
}
#display {
width: 300px;
height: 200px;
margin: 30px auto;
background-color: lightgray;
display: flex;
align-items: center;
justify-content: center;
font-size: 32px;
}
button {
font-size: 18px;
padding: 10px 20px;
}
</style>
</head>
<body>
<h1>Choose a Color</h1>
<div id="display">Choose a color</div>
<button class="colorButton">tomato</button>
<button class="colorButton">gold</button>
<button class="colorButton">skyblue</button>
<button class="colorButton">seagreen</button>
<script>
/*
HUMAN DESCRIPTION
1. Find the large display box.
2. Find all of the color buttons.
3. Go through the buttons one at a time.
4. Make each button listen for a click.
5. When a button is clicked, find out which color
that button represents.
6. Send that color to a function.
7. The function changes the background color of the box
and puts the color name inside it.
*/
/*
JAVASCRIPT LOGIC
1. Create a variable for the display box.
2. Create a variable that contains all of the color buttons.
3. Loop through the buttons one at a time.
4. Add a click event listener to each button.
5. When a button is clicked, get that button's color.
6. Pass the color into a function as a parameter.
7. In the function, change the display box's background color
and text using that parameter.
*/
</script>
</body>
</html>
Solution 1: Using a for loop
<script>
const display = document.querySelector("#display");
const buttons = document.querySelectorAll(".colorButton");
function changeColor(color) {
display.style.backgroundColor = color;
display.textContent = color;
console.log("new color:", color);
}
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
const color = buttons[i].textContent;
console.log("button index:", i);
console.log("color:", color);
changeColor(color);
});
}
</script>
Solution 2: Using forEach()
<script>
const display = document.querySelector("#display");
const buttons = document.querySelectorAll(".colorButton");
function changeColor(color) {
display.style.backgroundColor = color;
display.textContent = color;
}
buttons.forEach(function(button) {
button.addEventListener("click", function() {
const color = button.textContent;
changeColor(color);
});
});
</script>
Review JavaScript and the DOM:
Traversing // get to elements on the page
-
document.getElementById("bio")
Selects one element by its ID. -
document.getElementsByClassName("stanza")
Selects all elements with a class name (returns an HTMLCollection). -
document.getElementsByTagName("p")
Selects all elements by tag name (like all paragraphs). -
document.querySelector("#bio")
Selects the first element that matches a CSS selector. -
document.querySelectorAll(".stanza")
Selects all elements that match a CSS selector (returns a NodeList). -
element.parentElement
Gets the parent of an element. -
element.children
Gets all child elements inside a parent. -
element.firstElementChild
Gets the first child element. -
element.lastElementChild
Gets the last child element. -
element.nextElementSibling
Gets the next element at the same level. -
element.previousElementSibling
Gets the previous element at the same level.
Creating & Adding Elements // create new elements and add them to the page
-
document.createElement("tag")
Creates a new HTML element (but does not add it to the page yet).// Demo const p = document.createElement("p"); p.textContent = "Hello world"; -
parent.appendChild(element)
Adds a new element inside a parent (at the end).// Demo const div = document.getElementById("output"); div.appendChild(p); -
parent.append(element)
Adds an element (or text) inside a parent.// Demo div.append("More text"); -
parent.prepend(element)
Adds an element to the beginning of a parent.// Demo div.prepend(p); -
element.remove()
Removes an element from the page.// Demo p.remove(); -
parent.removeChild(element)
Removes a specific child element.// Demo div.removeChild(p); -
element.cloneNode(true)
Copies an element (true copies all children too).// Demo const copy = p.cloneNode(true); div.appendChild(copy); -
element.insertAdjacentHTML(position, html)
Inserts HTML directly into the page.// Demo div.insertAdjacentHTML("beforeend", "<p>New paragraph</p>");
Forms: Accessing Values
-
element.value// gets the value of an input, textarea, or select// Demo (text input) const nameInput = document.getElementById("name"); console.log(nameInput.value); -
element.checked// returns true or false (checkbox or radio)// Demo (checkbox) const agreeBox = document.getElementById("agree"); console.log(agreeBox.checked);
JavaScript Methods (in-built functions):
Math Methods:
Math.random()// returns a random number from 0 (inclusive) up to but not including 1Math.round()// rounds a number to the nearest integerMath.floor()// rounds a number DOWN to the nearest integerMath.max()// returns the number with the highest valueMath.min()// returns the number with the lowest valu
Switch vs Conditionals
// Example using switch
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Other day");
}
// Example using else if
let day = 3;
if (day === 1) {
console.log("Monday");
} else if (day === 2) {
console.log("Tuesday");
} else if (day === 3) {
console.log("Wednesday");
} else {
console.log("Other day");
}
Array Methods
-
.split(separator)
Splits a string into an array of substrings.
// Demo const word = "array"; const letters = word.split(""); // ["a","r","r","a","y"] -
.join(separator)
Joins all array elements into a single string.
// Demo ["_","_","_"].join(" "); // "_ _ _" ["c","a","t"].join(""); // "cat" -
.indexOf(value)
Returns the index of the first match, or -1 if not found.
// Demo const tried = ["a","e"]; tried.indexOf("a"); // 0 tried.indexOf("z"); // -1 -
.push(value)
Adds an element to the end of an array.
// Demo const tried = ["o","p"]; tried.push("q"); // ["o","p","q"] -
.pop()
Removes the last element from an array.
// Demo const letters = ["a","b","c"]; letters.pop(); // removes "c" -
.shift()
Removes the first element from an array.
// Demo const letters = ["a","b","c"]; letters.shift(); // removes "a" -
.unshift(value)
Adds an element to the beginning of an array.
// Demo const letters = ["b","c"]; letters.unshift("a"); // ["a","b","c"] -
.includes(value)
Returns true if the value exists in the array.
// Demo const letters = ["c","a","t"]; letters.includes("a"); // true letters.includes("z"); // false -
.slice(start, end)
Returns a portion of an array without changing the original.
// Demo const numbers = [1,2,3,4]; numbers.slice(1,3); // [2,3] -
.splice(start, count)
Removes or replaces elements in an array.
// Demo const numbers = [1,2,3,4]; numbers.splice(1,2); // removes 2 and 3 -
.sort()
Sorts the elements of an array. (Changes the original array.)// Demo (strings) const letters = ["b","a","d","c"]; letters.sort(); // ["a","b","c","d"] -
.sort(compareFunction)
When sorting numbers, you must provide a compare function.// Demo (numbers) const numbers = [10, 2, 30, 4]; // Without compare function (incorrect for numbers) numbers.sort(); // [10, 2, 30, 4] (sorted as text!) // Correct numeric sort numbers.sort(function (a, b) { return a - b; }); // [2, 4, 10, 30]
Array Iterators
-
.forEach(callback)
Runs a function once for each element in the array.
// Demo const letters = ["c","a","t"]; letters.forEach(function (ch, i) { console.log(i, ch); }); -
.map(callback)
Creates a new array by transforming each element.
// Demo const letters = ["a","r","r","a","y"]; const blanks = letters.map(function () { return "_"; }); // ["_","_","_","_","_"] -
.filter(callback)
Creates a new array with elements that pass a test.
// Demo const numbers = [1,2,3,4,5]; const evens = numbers.filter(function (num) { return num > 3; }); // [4,5] -
.find(callback)
Returns the first element that passes a test.
// Demo const numbers = [5,12,8,130]; const big = numbers.find(function (num) { return num > 10; }); // 12 -
.some(callback)
Returns true if at least one element passes a test.
// Demo const numbers = [1,3,5,8]; numbers.some(function (num) { return num % 2 === 0; }); // true -
.every(callback)
Returns true if all elements pass a test.
// Demo const numbers = [2,4,6]; numbers.every(function (num) { return num % 2 === 0; }); // true
forEach() (very useful)
forEach() - w3schoolsforEach() Demo
Use forEach() when you simply want to do the same thing to every item in a list. Use a for loop when you need more control over the loop. One advantage of a for loop is that the variable i gives you a counting number that can also be used as the index of the current item.
Slider/Menu Site: 5% DUE: 10/7
You will receive a provided HTML and CSS structure containing an image slider and animated navigation menu. Your task is to write the JavaScript that makes the interface work.
This is primarily a logic and problem-solving project. You should be able to explain how each event, function, variable, and state change contributes to the slider and menu behavior. Think as an interaction designer: this is a showpiece for your portfolio.
Minimum Requirements
- Working previous and next controls
- Correct image or content indexing
- A functional animated navigation menu
- Clear organization using functions and variables
- Numbered logic steps in a comment before the script
- No frameworks, libraries, or AI-generated code
Logic Steps (required)
At the top of your <script>, before any code, write your numbered logic steps as a commented list. For example:
/*
1. Select all the slides and store the current index (start at 0).
2. Write showSlide(index): hide all slides, show the one at index.
3. nextSlide(): add 1 to the index; if past the end, loop to 0; showSlide.
4. prevSlide(): subtract 1; if below 0, loop to the last; showSlide.
5. Add click listeners on the next and prev buttons.
6. Toggle the menu open/closed on the menu button click.
*/