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 9/16)
Clickable Page (5%) (complete with CSS design) (Due 9/30)
Module Notes
Last Week's Challenging Challenges
Challenge 1: Personal Greeting
- Ask the viewer for their name using
prompt(). - Display a greeting on the page that includes their name using
document.write().
Challenge 2: Age Calculator
- Ask the viewer for their age using
prompt(). - Convert the string input to a number using
parseInt(), then calculate how old they will be in 10 years. -
Display a message on the page using
document.write()that includes:- Their current age
- Their age in 10 years
Note: parseInt() turns a string containing a number into an integer that JavaScript can use for math.
let number = "8";
let integer = parseInt(number);
Challenge 3: Yes / No Decision
- Ask the viewer a yes/no question using
confirm(). - Use an
if / elsestatement to display a different message on the page depending on their answer.
Challenge 4: Favorite Movies List — Arrays
- Create an array containing three of your favorite movies as strings.
-
Display:
- How many items are in the array
- The first item in the array
- The last item in the array
Hint: To access the last item, use array.length - 1.
Functions, Arrays & Loops:
Syntax Exercises
- DOM selection
- "Functions"
- "Scope"
- "Loops"
Download this "lesson2" file for the next exercises.
WORKSHOP
These challenges are arranged from simpler to more complex. Read the Logic Steps first. We will discuss the approach as a class, then you will work out the JavaScript syntax on your own. Open the solution only after you have made a real attempt.
- Download the JavaScript Challenges starter template.
- Open the template in VS Code. The HTML buttons and output elements for all five challenges are already provided.
- Write your JavaScript in the
<script>area at the bottom of the page. - Work through the challenges in order. Use the Logic Steps to plan what the script needs to do before working out the syntax.
- The challenges combine variables, conditionals, click events, functions, arrays, for loops, and Math.random().
- Challenges 4 and 5 are intentionally more difficult and combine several ideas at once.
- Keep JS Demo Lesson 2 open for syntax examples and reference.
- Open each challenge's solution only after you have made a real attempt to write the script yourself.
New Challenges
Each challenge needs its own button or buttons, an output element, and JavaScript that connects the click event to a function. The goal is to translate the logic steps into syntax.
Challenge 1: Is It In the List?
The user types a word. The program checks whether that word exists in an array.
Logic Steps
- Create an array of words.
- Create a button and an output element in the HTML.
- Connect the button click to a function.
- Inside the function, ask the user for a word with
prompt(). - Create a variable that begins as
falseto remember whether a match has been found. - Use a for loop to go through the array one item at a time.
- Inside the loop, use a conditional to compare each array word with the user's word.
- If a match is found, change the variable to
true. - After the loop, display either “Found” or “Not Found.”
Show one working solution
<button id="checkBtn">Check Word</button>
<div id="output"></div>
<script>
const words = ["apple", "banana", "grape", "orange"];
const checkBtn = document.getElementById("checkBtn");
const output = document.getElementById("output");
checkBtn.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}`;
}
}
</script>
Challenge 2: Count the Matches
The user types a number. The program counts how many times that number appears in an array.
Logic Steps
- Create an array of numbers with at least one repeated value.
- Create a button and an output element.
- Connect the button click to a function.
- Inside the function, ask the user for a number and convert the input to a number.
- Create a counter variable that begins at
0. - Use a for loop to go through the array.
- If the current array number matches the user's number, increase the counter by 1.
- After the loop, display the final count.
Show one working solution
<button id="countBtn">Count Matches</button>
<div id="output"></div>
<script>
const numbers = [2, 5, 7, 5, 9, 5, 1];
const countBtn = document.getElementById("countBtn");
const output = document.getElementById("output");
countBtn.addEventListener("click", countMatches);
function countMatches() {
const input = prompt("Type a number to count:");
let count = 0;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] == input) {
count++;
}
}
output.textContent = `${input} appears ${count} time(s).`;
}
</script>
Challenge 3: Above, Below, or Equal?
The user enters a number. The program sorts the values in an array into three groups: above, below, or equal to that number.
Logic Steps
- Create an array of numbers.
- Create a button and an output element.
- Connect the button click to a function.
- Inside the function, ask the user for a comparison number.
- Create three counters:
above,below, andequal. Start each at 0. - Use one for loop to go through the array.
- For each number, use
if / else if / elseto decide which counter should increase. - After the loop, display all three totals.
Show one working solution
<button id="compareBtn">Compare Numbers</button>
<div id="output"></div>
<script>
const numbers = [4, 12, 9, 12, 27, 3, 18];
const compareBtn = document.getElementById("compareBtn");
const output = document.getElementById("output");
compareBtn.addEventListener("click", compareNumbers);
function compareNumbers() {
const input = parseInt(prompt("Type a comparison number:"));
let above = 0;
let below = 0;
let equal = 0;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > input) {
above++;
} else if (numbers[i] < input) {
below++;
} else {
equal++;
}
}
output.textContent =
`Above: ${above} | Below: ${below} | Equal: ${equal}`;
}
</script>
Challenge 4: Guess the Secret Word — More Challenging
Three word choices appear as buttons. One of them is randomly chosen as the secret word. The player keeps clicking until they find it.
Logic Steps
- Create an array containing three possible words.
- Create three buttons and an output element.
- Put one array word on each button.
- Randomly select one word from the array and store it as the secret word.
- Connect each word button to the same checking function.
- When a button is clicked, send that button's word to the checking function.
- Inside the function, compare the clicked word with the secret word.
- If they match, display “Correct!” and disable all three buttons.
- If they do not match, display “Try again.”
Show one working solution
<button id="btn1"></button>
<button id="btn2"></button>
<button id="btn3"></button>
<div id="output"></div>
<script>
const words = ["apple", "banana", "cherry"];
const btn1 = document.getElementById("btn1");
const btn2 = document.getElementById("btn2");
const btn3 = document.getElementById("btn3");
const output = document.getElementById("output");
btn1.textContent = words[0];
btn2.textContent = words[1];
btn3.textContent = words[2];
const secretWord =
words[Math.floor(Math.random() * words.length)];
btn1.addEventListener("click", function () {
checkGuess(words[0]);
});
btn2.addEventListener("click", function () {
checkGuess(words[1]);
});
btn3.addEventListener("click", function () {
checkGuess(words[2]);
});
function checkGuess(clickedWord) {
if (clickedWord === secretWord) {
output.textContent = "Correct!";
btn1.disabled = true;
btn2.disabled = true;
btn3.disabled = true;
} else {
output.textContent = "Try again.";
}
}
</script>
Challenge 5: Roll a 6 — More Challenging
Click the button to roll a die. Keep track of how many rolls it takes to get a 6.
Logic Steps
- Create a variable to count the number of rolls. Start it at
0. - Connect the Roll Die button to a function.
- Each time the button is clicked, increase the roll counter by 1.
- Generate a random whole number from 1–6.
- Display the die result and the number of rolls.
- If the result is 6, display a winning message and disable the button.
Show one working solution
<button id="rollBtn">Roll Die</button>
<div id="output"></div>
<script>
let rollCount = 0;
const rollBtn = document.getElementById("rollBtn");
const output = document.getElementById("output");
rollBtn.addEventListener("click", rollDie);
function rollDie() {
rollCount++;
const roll = Math.floor(Math.random() * 6) + 1;
output.innerHTML =
`You rolled: ${roll}<br>
Rolls: ${rollCount}`;
if (roll === 6) {
output.innerHTML += "<br><strong>You rolled a 6!</strong>";
rollBtn.disabled = true;
}
}
</script>