For loops
Open the for_loops.js in your text editor and solve the challenges listed. Refer to the reference section for help.
Another practical example
Let's return to your earliest years in school. If you recall, one of the first songs you had to learn was the ABC song. You know how it goes... "A B C D E F G...", to the same melody as "Twinkle Twinkle Little Star". The purpose of that song was to get you to memorize all 26 letters of the alphabet, which is actually quite a feat if you think about it. When was the last time you had to memorize 26 of anything? You were a genius back then!
Anyway, the ABC song requires you to sing each letter out loud, like this:
A B C D E F G,
H I J K L M N O P,
Q R S,
T U V,
W X,
Y and Z
Now I know my ABCs
Next time won't you sing with me?
Now, in your head you're probably not counting to 26. You might not have even known that there are actually 26 letters, which is fine. Instead, you start at A and continue singing each letter until you reach the end of the alphabet, however long it is. For now let's just call it alphabet.length
. Once you reach alphabet.length
, you're done, and can add the big finisher at the end.
If your mind only spoke JavaScript, here's how it might communicate what you did as a kid:
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (let i = 0; i < alphabet.length; i++) {
console.log(alphabet.charAt(i));
}
This is a basic example of a for loop!
for loop syntax. {{ REPLACE THIS SECTION}}
For reference, here's the basic structure of a for loop:
for ([initialization]; [condition]; [update]) {
}
In JavaScript, a for loop begins with the keyword for
, followed by three setup statements enclosed in parentheses:
false
, exactly like a while loop. Ends with a semicolon.Note that while all three expressions are optional, you must include the two semicolons no matter what.
for loop step-by-step
There's obviously a lot to unpack here, especially compared to the straightforward syntax of while loops.
The first thing you should know is that, for all intents and purposes, while loops and for loops are functionally interchangeable. To prove it, let's write a for loop that counts from 1 to 12, just as we did with a while loop earlier. Because we're just starting, we'll walk through it step by step.
Step 1: Write the outline. The outline should just be the word "for", a pair of parentheses, and a pair of curly braces. Inside the parentheses place to semicolons, just so you don't forget them.
for (;;) {
}
Step 2: Initialize a counter variable. This happens just once, and before the loop begins. Note that this is identical to what we did with our while loop earlier; however, here, the initialization is actually part of the for loop's setup, not a separate thing as it is with while loops.
for (let count = 1;;) {
}
Step 3: Write the logical expression you'll be checking for each time through the loop. This should go before the second semicolon.
for (let count = 1; count <= 12;) {
}
Step 4: Write your increment statement. This is the "update" that occurs after each iteration through the loop. Again, identical to how we did the while loop, only here it is also part of the loop setup.
for (let count = 1; count <= 12; count++) {
}
Step 5: Write all code you'd like to repeat within the curly braces. For us, it's simply printing the value of count each time.
for (let count = 1; count <= 12; count++) {
console.log(count);
}
And that's all folks! Try it out in the REPL:
> for (let count = 1; count <= 12; count++) {
... console.log(count);
... }
1
2
3
4
5
6
7
8
9
10
11
12
undefined
Same result (except here we don't get a handy printout of count
's final value, just undefined
... but oh well).
While we're at it, let's also try making this code loop infinitely by simply removing the increment expression.
> for (let count = 1; count <= 12;) {
... console.log(count);
... }
1
1
1
1
Can we also translate the dreaded while (true)
infinite into a for
loop? You bet! But we'll leave you to figure out how... mwahahaha...
Looping through lists with for loops
Let's return to our practical example: the ABC problem.
Let's think of the alphabet is one long string, from A to Z.
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
If you recall, a string is basically a list of one-character strings concatenated together. We can access each individual character by its index using the str.charAt()
method. So alphabet.charAt(0)
returns "A"
, and so forth. Basically, if we had a variable that could start at index 0 and increment up to alphabet.length
, we could access every single character in the alphabet
string.
When looping through lists (or using any kind of for loop, really), we usually label this "indexing" variable i
. This is just convention, since as Shakespeare taught us, a name by any other rose would sweet just as smell! Wait...
Hey! Let's try it out in the REPL:
> let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
undefined
> for (let i = 0; i < alphabet.length; i++) {
... console.log(alphabet.charAt(i));
... }
A
B
...
Z
undefined
Beautiful!
A new way to flow
Recall our lesson on control flow. So far you have used two of the three control structures: sequence (default, top-to-bottom processing) and selection (if/else, branching paths). Loops are repetition control structures, in that they enable programs to repeat sections of code a certain number of times, or until certain conditions are met.
Loops can be hard to grasp at first. The cool thing is that we use loops in real life all the time! In fact, you'd be surprised at how "programming-like" our thinking can be. Even as young children, we have a strong grasp of many programming concepts, including loops. Without loops, we probably wouldn't even be able to count!
In short, if we can understand how we think in terms of loops, we can better implement this thinking with code.
There are two kinds of loops you need to know about, and we'll cover them both in this lesson!
Practical example
Before we get started, let's do an exercise: count to 12 out loud. Go ahead, we'll wait. =)
Done? Okay, now let's take a peek into what might have been going on in your head while you were counting.
First, how did you keep track of what number you were currently on? You remembered it, hmm? It's like you had a variable called count
that began at 1 and incremented each time you said a number out loud.
Second, how did you know when to stop counting? When you said "12", right? When count
became 12, you knew you were done.
Another way of putting it: While count
was less than or equal to 12, you continued to say the value of count
, then increment it.
If your mind only spoke JavaScript, here's how it might communicate what it just did:
let count = 1;
while (count <= 12) {
console.log(count);
count++;
}
This is a basic example of a while
loop!
while loop syntax
In JavaScript, a while loop begins with the keyword while
, followed by a logical expression enclosed in parentheses, and ending with a block of code enclosed in curly braces. If the logical expression in the parentheses evaluates to true
, then the block of code in the curly braces will repeat; otherwise, that block of code will be skipped over entirely.
let bar = 1;
while (bar < 10) {
bar++;
}
Syntactically, while loops are identical to if statements, and for good reason. Actually, you can think of a while loop as a repeated if statement. The main difference is that the if statement only checks the logical expression in the parentheses once, and the while loop checks it over and over until it is false.
Let's try some while loops in the Node REPL.
First, let's try the counting loop we started with. You can enter multi-line coding blocks in the REPL just as you would in a script.
> let count = 1;
undefined
> while (count <= 12) {
... console.log(count);
... count++;
... }
1
2
3
4
5
6
7
8
9
10
11
12
12
That last 12
printout is simply the REPL telling you the final value of count
after the loop. Pretty handy if you weren't printing it each time!
Notice that we are increment count
each time we iterate through the loop. What would happen if we didn't? Try it!
> let count = 1;
undefined
> while (count <= 12) {
... console.log(count);
... }
1
1
1
1
1
1
1
Oh no! You've triggered an infinite loop! Quick! Kill the infinite loop by hitting CTRL + C on your keyboard! You might need to do this a few times for it to work.
Whew! Well, we might as well tell you about infinite loops now.
An infinite loop is a loop that will never, ever, ever, ever, ever, ever, ever, ever, ever, ever, ever, ever, ever, ever, ever, ever, ever... EVER end!!!
Textbook example (don't do this!):
while (true) {
console.log("I TOLD YOU NOT TO DO THIS!!!");
}
The boolean value true
is obviously always going to be true
, so this ride will never end!
Beware infinite loops, my friend!