Welcome back. Last time we looked at how to run code only based on some other condition. Loops build upon that by letting you rerun code multiple times based on some condition.
The most common type of loop in Javascript is a for-loop. For loops use a variable, a condition, and a step to run some code multiple times. This is most easily explained by an example:
for (let i = 0; i < 5; i+= 1) {
console.log("i = " + i);
}
// Outputs:
// 0
// 1
// 2
// 3
// 4
The three parts of the for loop are inside the parentheses, and are separated by semicolons. The first part, sometimes called the initialization, is done before any loops are run. Then, the condition is checked. As long as the condition is true, the body (which is the code inside the braces) is run. Finally, the step code (the i+= 1) is run, and the code jumps back up to check the condition again.
Here’s what that would look like in Javascript:
// transformed for loop
let i = 0;
// <- Jump to here from the bottom of the loop
if (i < 5) {
same code body from above.
// now the step code runs
i += 1;
// now the program jobs back up to the comment above.
}
Remember how strings (text) are like collections of letters? It is very common to use a for loop to do something for each letter of a string.
let msg = 'this is a secret message';
let new_msg = '';
for (let i = 0; i < msg.length; i++) {
// This looks up the position of each letter in the
// alphabet, shifts it one to the right, then
// adds the shifted letter to new_msg.
let old_letter_code = msg.charCodeAt(i);
let new_letter_code = old_letter_code + 1;
if (new_letter_code > 'z'.charCodeAt(0)) {
// wrap around, z -> a
new_letter_code = 'a'.charCodeAt(0);
}
new_msg += String.fromCharCode(new_letter_code);
}
console.log(new_msg);
This very basic form of encryption, which shifts each letter by the same amount, is called the Caesar Shift.
You can see the documentation for fromCharCode and charCodeAt to understand the new functions used.
Once you understand the for loop, the other loops are simple by comparison. A while loop is a bit like a for loop, but it only has a condition. The body of the loop must either:
Here’s a little snippet that draws a sort of half-tree.
let height = 1;
while (height < 10) {
// this just gives is a star, repeated some number
// of times
let line = "*".repeat(height);
console.log(line);
height += 1;
}
These are very rare in Javascript. You can almost always use one of the loops above instead. The difference between a do-loop and a while loop is that a do loop is guaranteed to run the loop body at least once, since the condition is checked at the end.
let i = 1;
do {
console.log(i);
i++;
} while (i < 0);
// outputs 1;
Continue until the number 1 is reached. Prompt for an input, then display the Collatz sequence for that number.
You can use this function to check for even vs odd:
function is_even(num) {
// the % operator gives you the remainder after dividing.
return (num % 2) == 0;
}
let sum = 0;
for (let i = 0; i <= 100; i++) {
sum += i;
}
console.log(sum); // 5050
let input = prompt('your message: ');
let new_str = '';
for (let i = input.length - 1; i >= 0; i--) {
new_str += input[i];
}
console.log(new_str);
let n = prompt('starting number: ');
console.log(n);
while (n != 1) {
if (n % 2 == 0) {
n /= 2;
} else {
n = n*3 + 1;
}
console.log(n);
}
At the end of the previous lesson, I mentioned that you already know eveything needed. But how do you loop without loops? In the next lesson, we’ll look at recursion which is a way of repeating, and more, using only functions.