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 Feb 5)

Interactive Website (5%) (complete with CSS design) (Due Feb 12)

Hangman Game (complete with CSS design) (Due Feb 19)


Module Notes

Functions, Arrays & Loops:


WORKSHOP

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
  1. Create an array of possible words.
  2. Show three array word choices on the page (as buttons).
  3. Pick one secret word at random when the page loads and store it in a variable.
  4. Set a number of attempts (for example: 3) and store it in a variable.
  5. Show three word choices on the page (as buttons).
  6. When a word button is clicked, read the clicked word (button text or data attribute).
  7. If the clicked word matches the secret word, display “Correct” and stop the game.
  8. If it does not match, subtract 1 attempt and display “Try again” and attempts left.
  9. If attempts reach 0, display the secret word and stop the game.

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

  1. Create two variables to store each player’s score.
  2. Create one button on the page (HTML)
  3. Each button click runs one round of the game.
  4. Generate a random number between 1 and 6 for Player 1.
  5. Generate a random number between 1 and 6 for Player 2.
  6. 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.
  7. Display both dice rolls and the updated scores on the page.
  8. If a player reaches the target score, display the winner and stop the game.

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
  1. Create one array of words.
  2. Add one button and connect it to a function.
  3. When clicked, use prompt() to ask the user for a word.
  4. Use one for loop to go through the array.
  5. Use one conditional to check if the user’s word matches the current array word.
  6. If a match is found, store that result (example: set a variable like “found” to true).
  7. 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
  1. Create one array of numbers (include some repeats).
  2. Add one button and connect it to a function.
  3. When clicked, use prompt() to ask the user for a number.
  4. Create a counter variable starting at 0.
  5. Use one for loop to go through the array.
  6. Use one conditional to check if the current number matches the user’s input.
  7. If it matches, increase the counter.
  8. 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 (String(nums[i]) === input) {
      count = count + 1;
    }
  }

  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
  1. Create one array of numbers.
  2. Add one button and connect it to a function.
  3. When clicked, use prompt() to ask the user for a threshold number.
  4. Create a counter variable starting at 0.
  5. Use one for loop to go through the array.
  6. Use one conditional to check if the current number is greater than the threshold.
  7. If it is greater, increase the counter.
  8. 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 = count + 1;
    }
  }

  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
  1. Create one array that contains "yes" and "no" values.
  2. Add one button and connect it to a function.
  3. When clicked, use prompt() to ask the user to type either "yes" or "no".
  4. Create a counter variable starting at 0.
  5. Use one for loop to go through the array.
  6. Use one conditional to count how many times the user’s input appears in the array.
  7. 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
  1. Create one array of numbers (positive and negative).
  2. Create a variable called score that starts at 0 and persists between clicks.
  3. Add one button and connect it to a function.
  4. When clicked, use confirm() to ask “Take a risk?”
  5. If the user cancels, stop the function (no changes).
  6. If the user confirms, use Math.random and Math.floor to select a random number from the array.
  7. Add it to score and 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 = 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
  1. Create one array of allowed categories (example: "action", "comedy", "drama").
  2. Add one button and connect it to a function.
  3. When clicked, use prompt() to ask the user for a category.
  4. Use one for loop to check the array for a match.
  5. Use one conditional to detect a match while looping.
  6. After the loop, use one conditional to either accept the category or display “Not an option.”
  7. 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 12 

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