Week 3: Functions, Arrays & Loops
To Do This Week:
CodeAcademy: Complete the following lessons (not the projects) from the Learn JavaScript module:- "Functions"
- "Scope"
- "Arrays"
- "Loops"
Upcoming Assignments
JavaScript Codecademy #1 (DUE Feb 5)
Interactive Website (5%) (complete with CSS design) (Due Feb 19)
Hangman Game (complete with CSS design) (Due Feb 26)
Module Notes
Functions, Arrays & Loops:
WORKSHOP
- Create a NEW page (new
.htmlfile) and write your own HTML + JavaScript from scratch. - Each challenge must be triggered by at least one button using
addEventListener("click", ...). - Every challenge must use: functions, arrays, conditionals, Math.random(), and at least one loop.
- At least one challenge must include scope: global state that changes over time.
- JS Demo Lesson 2
Last Week's Challenging Challenges
Challenge 2: Guess the Secret Word (Click Choices)
The page picks one secret word. The player clicks one of three word buttons to guess it.
Logic Steps
- Create an array of possible words.
- Select three array word, add them to a new array and make them buttons on the page.
- Randomly pick one secret word from the three and store it in a variable.
Show three word choices on the page (as buttons).- When a word button is clicked, run a function to see if the clicked word matches secret word.
- If the clicked word matches the secret word, display “Correct” and stop the game.
- If it does not match, display “Try again”.
Show one working solution
const words = ["apple", "banana", "cherry", "grape", "orange"];
const word1 = words[Math.floor(Math.random() * words.length)];
let word2 = words[Math.floor(Math.random() * words.length)];
while (word2 === word1) {
word2 = words[Math.floor(Math.random() * words.length)];
}
let word3 = words[Math.floor(Math.random() * words.length)];
while (word3 === word1 || word3 === word2) {
word3 = words[Math.floor(Math.random() * words.length)];
}
const choices = [word1, word2, word3];
const secretWord = choices[Math.floor(Math.random() * choices.length)];
const btn1 = document.getElementById("btn1");
const btn2 = document.getElementById("btn2");
const btn3 = document.getElementById("btn3");
btn1.textContent = word1;
btn2.textContent = word2;
btn3.textContent = word3;
function checkGuess(clickedWord) {
if (clickedWord === secretWord) {
console.log(`Correct!`);
} else {
console.log(`Try again.`);
}
}
btn1.addEventListener("click", function () {
checkGuess(btn1.textContent);
});
btn2.addEventListener("click", function () {
checkGuess(btn2.textContent);
});
btn3.addEventListener("click", function () {
checkGuess(btn3.textContent);
});
console.log(`Secret word: ${secretWord}`);
Challenge 3: Dice Race
Two players roll a die each round. The player with the higher roll earns 1 point. First player to reach the target score wins.
Logic Steps
- Create two variables to store each player’s score.
- Create one button on the page (HTML)
- Each button click runs one round of the game.
- Generate a random number between 1 and 6 for Player 1.
- Generate a random number between 1 and 6 for Player 2.
-
Compare the two rolls:
- If Player 1’s roll is higher, Player 1 gains 1 point.
- If Player 2’s roll is higher, Player 2 gains 1 point.
- If the rolls are equal, no points are awarded.
- Display both dice rolls and the updated scores on the page.
- If a player reaches the target score, display the winner and stop the game.
Show one working solution
// Assumes a button with id "rollBtn" and a div with id "output" in HTML
let p1Score = 0;
let p2Score = 0;
const targetScore = 5;
const rollBtn = document.getElementById("rollBtn");
const output = document.getElementById("output");
function playRound() {
if (p1Score >= targetScore || p2Score >= targetScore) {
return;
}
const p1Roll = Math.floor(Math.random() * 6) + 1;
const p2Roll = Math.floor(Math.random() * 6) + 1;
let roundResult = "";
if (p1Roll > p2Roll) {
p1Score = p1Score++;
roundResult = "Player 1 wins the round.";
} else if (p2Roll > p1Roll) {
p2Score = p2Score++;
roundResult = "Player 2 wins the round.";
} else {
roundResult = "Tie round. No points awarded.";
}
output.innerHTML =
`Player 1 rolled: ${p1Roll}
Player 2 rolled: ${p2Roll}
${roundResult}
Score — Player 1: ${p1Score} | Player 2: ${p2Score}`;
if (p1Score >= targetScore) {
output.innerHTML += `Player 1 wins the game!`;
rollBtn.disabled = true;
} else if (p2Score >= targetScore) {
output.innerHTML += `Player 2 wins the game!`;
rollBtn.disabled = true;
}
}
rollBtn.addEventListener("click", function () {
playRound();
});
BEGINNER CHALLENGES
Each challenge must include a button, an output element, and a script that connects the button to a function:
<button id="btn">Run</button>
<div id="output"></div>
Challenge 1: Is It In the List?
The user types a word. The program checks if that word exists in an array.
Logic Steps
- Create one array of words.
- Add one button and connect it to a function.
- When clicked, use
prompt()to ask the user for a word. - Use one for loop to go through the array.
- Use one conditional to check if the user’s word matches the current array word.
- If a match is found, store that result (example: set a variable like “found” to true).
- After the loop, use one conditional to display “Found” or “Not Found.”
Show Example Solution
// Challenge 1: Is It In the List?
const words = ["apple", "banana", "grape", "orange"];
const btn = document.getElementById("btn");
const output = document.getElementById("output");
btn.addEventListener("click", checkList);
function checkList() {
const input = prompt("Type a word:");
let found = false;
for (let i = 0; i < words.length; i++) {
if (words[i] === input) {
found = true;
}
}
if (found) {
output.textContent = `Found: ${input}`;
} else {
output.textContent = `Not found: ${input}`;
}
}
Challenge 2: Count the Matches
The user types a number. The program counts how many times it appears in an array.
Logic Steps
- Create one array of numbers (include some repeats).
- Add one button and connect it to a function.
- When clicked, use
prompt()to ask the user for a number. - Create a counter variable starting at 0.
- Use one for loop to go through the array.
- Use one conditional to check if the current number matches the user’s input.
- If it matches, increase the counter.
- Display the final count.
Show Example Solution
// Challenge 2: Count the Matches
const nums = [2, 5, 7, 5, 9, 5, 1];
const btn = document.getElementById("btn");
const output = document.getElementById("output");
btn.addEventListener("click", countMatches);
function countMatches() {
const input = prompt("Type a number to count:");
let count = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] == input) {
count++;
}
}
output.textContent = `Matches for ${input}: ${count}`;
}
Challenge 3: Above or Below?
The user types a threshold. The program counts how many array numbers are above it.
Logic Steps
- Create one array of numbers.
- Add one button and connect it to a function.
- When clicked, use
prompt()to ask the user for a threshold number. - Create a counter variable starting at 0.
- Use one for loop to go through the array.
- Use one conditional to check if the current number is greater than the threshold.
- If it is greater, increase the counter.
- Display how many numbers were above the threshold.
Show Example Solution
// Challenge 3: Above or Below?
const nums = [4, 12, 9, 27, 3, 18];
const btn = document.getElementById("btn");
const output = document.getElementById("output");
btn.addEventListener("click", countAbove);
function countAbove() {
const input = prompt("Type a threshold number:");
let count = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] > input) {
count++;
}
}
output.textContent = `Numbers above ${input}: ${count}`;
}
Challenge 4: “Y/N” Survey Count
The user answers a yes/no prompt. The program counts how many "yes" values exist in an array.
Logic Steps
- Create one array that contains "yes" and "no" values.
- Add one button and connect it to a function.
- When clicked, use
prompt()to ask the user to type either "yes" or "no". - Create a counter variable starting at 0.
- Use one for loop to go through the array.
- Use one conditional to count how many times the user’s input appears in the array.
- Display the result.
Show Example Solution
// Challenge 4: "Y/N" Survey Count
const answers = ["yes", "no", "yes", "yes", "no", "no", "yes"];
const btn = document.getElementById("btn");
const output = document.getElementById("output");
btn.addEventListener("click", countAnswer);
function countAnswer() {
const input = prompt('Type "yes" or "no":');
let count = 0;
for (let i = 0; i < answers.length; i++) {
if (answers[i] === input) {
count++;
}
}
output.textContent = `${input} count: ${count}`;
}
Challenge 5: Random Score Adder (User Chooses Risk)
The user decides whether to take a turn. If they confirm, the program adds a random number from the array to a running score.
Logic Steps
- Create one array of numbers (positive and negative).
- Create a variable called
scorethat starts at 0 and persists between clicks. - Add one button and connect it to a function.
- When clicked, use
confirm()to ask “Take a risk?” - If the user cancels, stop the function (no changes).
- If the user confirms, use Math.random and Math.floor to select a random number from the array.
- Add it to
scoreand display the updated score.
Show Example Solution
// Challenge 5: Random Score Adder (User Chooses Risk)
const nums = [5, -3, 10, -8, 2];
let score = 0;
const btn = document.getElementById("btn");
const output = document.getElementById("output");
btn.addEventListener("click", takeTurn);
function takeTurn() {
const ok = confirm("Take a risk?");
if (!ok) {
output.textContent = `No risk taken. Score: ${score}`;
return;
}
const i = Math.floor(Math.random() * nums.length);
const value = nums[i];
score += value;
output.textContent = `Picked: ${value} | Score: ${score}`;
}
Challenge 6: Pick a Category
The user types a category word. The program checks if it is one of the allowed categories in an array.
Logic Steps
- Create one array of allowed categories (example: "action", "comedy", "drama").
- Add one button and connect it to a function.
- When clicked, use
prompt()to ask the user for a category. - Use one for loop to check the array for a match.
- Use one conditional to detect a match while looping.
- After the loop, use one conditional to either accept the category or display “Not an option.”
- Display the result on the page (and optionally also use
alert()).
Show Example Solution
// Challenge 6: Pick a Category
const categories = ["action", "comedy", "drama"];
const btn = document.getElementById("btn");
const output = document.getElementById("output");
btn.addEventListener("click", pickCategory);
function pickCategory() {
const input = prompt("Pick a category: action, comedy, drama");
let allowed = false;
for (let i = 0; i < categories.length; i++) {
if (categories[i] === input) {
allowed = true;
}
}
if (allowed) {
output.textContent = `Accepted: ${input}`;
} else {
output.textContent = `Not an option: ${input}`;
alert("Try: action, comedy, or drama");
}
}
Interactive Website: 5% DUE: Thursday Feb 19
This assignment is designed to bring together your understanding of basic syntax, variables, conditionals, arrays, functions, and loops in JavaScript. The key objective is to create a dynamic website that allows for user interaction, resulting in changes on the webpage without altering the URL. *In all projects in this class you will include in the source code the natural language steps of your script.Add your commented out ( /*…*/ ) steps in a numbered list inside the <script> tag.Suggested Ideas for Your Website
- Interactive Quiz: A simple quiz where users answer questions, and get immediate feedback.
- Dynamic Photo Gallery: A gallery where users can filter or sort images based on categories.
- To-Do List: A task manager where users can add, mark, and delete tasks.
- Customizable Timer: A timer where users can set and start a countdown for various activities.
- A Digital Art Work: User interactivity creates dynamic displays of image, text, sound and/or video. The weirder the better.