Loops and Text
In the lesson on arrays, you saw that text isn't an array, but it has a .length, and you can read its characters by index: word[0] is the first character. That is all a loop needs, so you can go through text character by character, just like through an array:
const word = "Hello";
for (let i = 0; i < word.length; i++) {
console.log(word[i]);
}This prints:
H
e
l
l
oThe for...of loop works with text too. In each iteration, the variable holds the next character:
const word = "Hello";
for (const character of word) {
console.log(character);
}H
e
l
l
oThe patterns from the previous exercises work with text as well. This loop counts the letters l:
const word = "Hello";
let count = 0;
for (const character of word) {
if (character === "l") {
count++;
}
}
console.log("Number of l:", count);Number of l: 2Remember that uppercase and lowercase letters are different characters: "H" === "h" is false.
Instructions
Go through text with a loop and print each of its characters on its own line.
Below that, count how many times the letter r appears in text: create a variable count with the value 0, go through the text again and increase count by one for every r. After the loop, print console.log("Number of r:", count);. The output is Number of r: 2.