Week 3: Functions, Arrays & Loops

To Do This Week:

CodeAcademy: Complete the following lessons (not the projects) from the Learn JavaScript module:
  1. "Functions"
  2. "Scope"
  3. "Arrays"
  4. "Loops"
Optional Reading: Chapters from Eloquent JavaScript:

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

Challenge 2: Age Calculator

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

Challenge 4: Favorite Movies List — Arrays

Hint: To access the last item, use array.length - 1.


Functions, Arrays & Loops:


Syntax Exercises

  1. DOM selection
  2. "Functions"
  3. "Scope"
  4. "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.


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
  1. Create an array of words.
  2. Create a button and an output element in the HTML.
  3. Connect the button click to a function.
  4. Inside the function, ask the user for a word with prompt().
  5. Create a variable that begins as false to remember whether a match has been found.
  6. Use a for loop to go through the array one item at a time.
  7. Inside the loop, use a conditional to compare each array word with the user's word.
  8. If a match is found, change the variable to true.
  9. 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
  1. Create an array of numbers with at least one repeated value.
  2. Create a button and an output element.
  3. Connect the button click to a function.
  4. Inside the function, ask the user for a number and convert the input to a number.
  5. Create a counter variable that begins at 0.
  6. Use a for loop to go through the array.
  7. If the current array number matches the user's number, increase the counter by 1.
  8. 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
  1. Create an array of numbers.
  2. Create a button and an output element.
  3. Connect the button click to a function.
  4. Inside the function, ask the user for a comparison number.
  5. Create three counters: above, below, and equal. Start each at 0.
  6. Use one for loop to go through the array.
  7. For each number, use if / else if / else to decide which counter should increase.
  8. 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
  1. Create an array containing three possible words.
  2. Create three buttons and an output element.
  3. Put one array word on each button.
  4. Randomly select one word from the array and store it as the secret word.
  5. Connect each word button to the same checking function.
  6. When a button is clicked, send that button's word to the checking function.
  7. Inside the function, compare the clicked word with the secret word.
  8. If they match, display “Correct!” and disable all three buttons.
  9. 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
  1. Create a variable to count the number of rolls. Start it at 0.
  2. Connect the Roll Die button to a function.
  3. Each time the button is clicked, increase the roll counter by 1.
  4. Generate a random whole number from 1–6.
  5. Display the die result and the number of rolls.
  6. 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>
```