To Do This Week:
CodeAcademy: Complete the following lessons (not the projects) from the Learn JavaScript module:
- “Iterators”
- “Objects”
Read (Optional): Chapters from Eloquent JavaScript:
Interactive Website (Due Feb 5)
Module Notes
Hangman Game
- Extension until Friday January 31
- Add you natural language steps using Javascript terms, as best you can
- Comment out your list inside <script> and before your JavaScript
- Read carefully the script and try to understand each step. If you don’t understand a part of the script, go back to the same chat and ask for an explanation
Hangman Examples:
- https://dtc-wsuv.org/cbatson24/hangman/
- https://dtc-wsuv.org/lbeltman23/hangman/index.html
- https://dtc-wsuv.org/qcarrick24/Hangman/
Review JS Terms -m use them in your steps:
- Variables: Declare and initialize variables. Use
let
for values that can change andconst
for constants. - Strings: Text treated as literal strings, enclosed in quotes.
- Increment/Decrement: Use
i++
ori--
to increment or decrement a variable. - Comparison Operators: Use
>
,<
,&&
, and||
to compare values. - Conditionals: Use
if
,else if
, andelse
for conditional logic. - Arrays: Store lists of items that can be accessed by index.
- Functions: Encapsulate reusable logic with or without parameters.
- Scope: Understand the difference between global and local variables.
- For Loops: Perform repetitive tasks efficiently.
Arrays: Storage and Manipulation
Many of your projects used Arrays to store words for the game. As well as variables for the amount of guessed letters. To manipulate the words – ie. select a random word and hide the letters, etc, draws on Array Methods. There are a lot of them! Here are some common ones:
join()
: Combines guessed letters or the current game word into a readable string (guessedWord.join(" ")
for display).
const guessedWord = ['h', '_', 'l', '_', 'o']; // Current guessed letters
const displayWord = guessedWord.join(" "); // Combine with spaces
console.log(displayWord); // Output: "h _ l _ o"
split()
: Converts strings into arrays for easier iteration or manipulation (e.g., splittingselectedWord
for checking letters).
const selectedWord = "hello";
const lettersArray = selectedWord.split(""); // Split into individual letters
console.log(lettersArray); // Output: ["h", "e", "l", "l", "o"]fill()
: Used to initialize arrays with placeholder values like underscores (Array(selectedWord.length).fill('_')
).forEach()
: Used to iterate over arrays when you want to perform an action on each element without creating a new array.
const guessedWord = ['h', '_', 'l', '_', 'o'];
const displayWord = [];
// Empty array to store the transformed elements
guessedWord.forEach(function(char) {
if (char === '_') {
displayWord.push('_');
} else {
displayWord.push(char.toUpperCase());
}
});
console.log(displayWord.join(" ")); // Output: "H _ L _ O"
map()
: Applied to transform arrays for display purposes, such as converting_
to readable underscores with spaces.
const guessedWord = ['h', '_', 'l', '_', 'o'];
const displayWord = guessedWord.map(char => (char === '_' ? '_' : char.toUpperCase()));
console.log(displayWord.join(" ")); // Output: "H _ L _ O"
- Indexing: Arrays are accessed and updated to track guessed letters or hangman part visibility.
const guessedWord = ['_', '_', '_', '_', '_']; // Initially blank
guessedWord[1] = 'e'; // Correct guess for the second letter
guessedWord[3] = 'l'; // Correct guess for the fourth letter
console.log(guessedWord); // Output: ["_", "e", "_", "l", "_"]
Functions: Modular Game Features
Functions are heavily used to modularize tasks such as initializing the game, updating the word display, checking guesses, and managing the game state.
- Helper Functions: Small, single-purpose functions like
updateWordDisplay()
orrevealHangmanPart()
. - Event Handlers: Handle user interaction with buttons, such as letter clicks or resetting the game.
- Game Logic: Core functions like
checkGameStatus()
to handle win/loss conditions.
Game Initialization:
function startGame() {
selectedWord = words[Math.floor(Math.random() * words.length)];
guessedWord = Array(selectedWord.length).fill('_');
incorrectGuesses = 0;
displayWord();
displayLetters();
}
Word Display Update:
function displayWord() {
wordDisplay.textContent = guessedWord.join(" ");
}
DOM Manipulation
The scripts rely heavily on DOM methods to update the UI dynamically based on game state.
createElement
andappendChild
: Generate letter buttons dynamically.- Traversing elements:
document.querySelector()
,document.querySelectorAll()
querySelectorAll
: Select hangman parts or buttons for batch updates (e.g., disabling after a loss).addEventListener
: Attach click handlers for user interactions.
In-class Exercise:
Quick Review: Change Background Color
Background Change Do While
- variables
- click > function
- conditional
- increment
- loop
“What Thing Are You?” Quiz
Build a “What Thing Are You?” personality quiz that uses input and conditionals to display a fun result. Students expand the quiz with arrays and add personalized styling.
In class with a partner, describe in detail Quiz using “natural language” in ChatGPT to output the JavaScript based on your specific steps. Specify ES6, but no arrow functions….
Quiz Examples
Main Concepts: Variables, data types, conditionals, logical operators, user input, and basic JavaScript functions.
prompt templates for this course
Prompt for Beginner Students
“I am a beginner learning JavaScript. I need help thinking through a problem step-by-step before writing code. Here’s the problem I want to solve:
[describe your problem].
Can you help me break down the problem into clear steps in plain language? I will try at first using natural language with JavaScript terms as best I can. Please correct the logic of my steps and help me use the correct term. Once I have the steps right, I’d like you to guide me in translating them into JavaScript code with clear comments in teh script. Please use ES6 syntax but avoid arrow functions, ternary operators, and advanced array methods. Add comments to help me understand each part of the code.”
Prompt for Intermediate Students
“I have some experience with programming and want to practice solving a problem. I will describe the problem and outline the steps I think are needed to solve it:
[outline your problem].
Can you give me feedback on my outline and steps and suggest corrections if needed? After that, I’d like to write the JavaScript code for each step and get your feedback. Please guide me if I get stuck or make mistakes. Use ES6 syntax but avoid arrow functions, ternary operators, and advanced array methods. Add comments to explain the main steps in the script.”
Prompt for more Advanced Students
“I am familiar with JavaScript and want to improve my problem-solving skills. I’ll start by describing the problem and outlining the steps to solve it:
[outline your problem].
Can you review my outline and suggest any improvements? Once the outline is ready, I will write the complete JavaScript script for the problem. Please provide feedback on my code and suggest corrections where necessary. Use ES6 syntax but avoid arrow functions, ternary operators, and advanced array methods. I’d like to ensure my code is clear, efficient, and well-documented. Add comments to explain the main steps in the script to make clear my understanding.””
Review JavaScript and the DOM:
Traversing // get to elements on the page
document.querySelector('#bio")
document.querySelectorAll(".stanza")
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
String Methods:
charAt()
// returns the character at a specified indexconcat()
// joins two or more stringsincludes()
// checks if a string contains a specified value, returnstrue
orfalse
indexOf()
// returns the index of the first occurrence of a specified valuelastIndexOf()
// returns the index of the last occurrence of a specified valuereplace()
// replaces specified value(s) with another value in a stringslice()
// extracts a section of a string and returns it as a new stringsplit()
// splits a string into an array of substringsstartsWith()
// checks if a string begins with specified characters, returnstrue
orfalse
endsWith()
// checks if a string ends with specified characters, returnstrue
orfalse
toLowerCase()
// converts the entire string to lowercasetoUpperCase()
// converts the entire string to uppercasetrim()
// removes whitespace from both ends of a stringsubstring()
// returns the part of the string between the start and end indexesrepeat()
// repeats a string for a specified number of times
Array Methods:
pop()
// remove the last element of an arraypush()
// add a new item to an arrayshift()
// remove the first item of an arrayunshift()
// add new items to the beginning of an arraysplice()
// adds/removes items to/from an array, and returns the removed item(s)sort(), reverse()
// thesort()
method sorts an array alphabetically; for numbers, it sorts ascending/descending.reverse()
reverses the order of elementsslice()
// returns the selected elements in an array as a new array objectjoin()
// method returns an array as a string and does not change the original arraymap()
// creates a new array by applying a function to each element of the original arrayforEach()
// executes a provided function once for each array element, but does not return a new array
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) {
c onsole.log("Wednesday");
} else {
console.log("Other day");
}