Member-only story
Flavoring For Loops With Multiple If…Else Statements and a Dash of Booleans
While creating a ‘Hangman’ style game for my capstone JavaScript project I ran into an interesting problem regarding loops. Specifically, how can I loop through an array of characters in a word, and do only one thing if the character is part of the array, and only another thing if it’s not?
Outlining the Problem
I started by creating a function to split a word string into an array of characters:
// My ‘bank’ of words and clues:
var wordBank = [
["bumblebee", "buzz buzz"],
["jacket", "baby it’s cold outside"],
["yesterday", "not today or tomorrow but..."]
]// My function to split the word string into a character string and set it equal to arr:
function splitWord(word) {
arr = [...word];
console.log(arr);
}// run the function:
splitWord(wordBank[0][0]);// Output:
["b", "u", "m", "b", "l", "e", "b", "e", "e"]
I used the oninput
event in my input field to set the character entered to a variable automatically. When the ‘Check Letter’ button was clicked, it would run another function to compare that character to all the characters in my ‘bumblebee’ array.