A quick reminder before we start - control flow is the order in which instructions are executed within a program. One modifies control flow using control structures, expressions that alter the control flow based on given parameters. This reading will be covering the second of the main control structures you will use time and time again - loops.
When you finish this reading, you should be able to:
Imagine you are at a friend's house, and your friend has six dogs. Someone left the back gate open, and all the dogs go out in the yard and get super muddy. Now your friend wants to clean their dogs but they only have one bathtub! You can't wash all the dogs at once. So the only option is to give the dogs a bath one at a time until they are all clean. When you start, 0 dogs are clean and 6 dogs are dirty.
While there are still dirty dogs you still have a job to do. That is your condition - you will stop giving baths once all 6 dogs are clean. So after one bath you will have 1 clean dog and 5 dirty dogs. You've incremented (increased by one) your number of clean dogs. After each bath you check your condition again until you have 6 clean dogs - that's when you know you can stop!
What was described above is the idea of looping - setting a condition, executing an action, doing something to make sure the condition will be met eventually, and rechecking the condition before executing the next action.
Loops are a fundamental control structure for writing JavaScript. Loops will repeatedly execute a section of code while a condition is true. Loops are simple to write and incredibly powerful! There are many variations of loops but the two most fundamental loops will be covered now - while loops and for loops.
One of the simplest loops in JavaScript is the while loop. As with all loops, the while loop will execute a block of code as long as a specified condition is true. The while loop starts with the keyword while then states a condition in parentheses. The code in the following braces will be run as long as the above condition is met.
while (condition) {
// code block to be executed
}
In the following example, the code in the loop will run, over and over again, as long as a variable (index) is less than 10:
let index = 0;
// this is the condition that will be checked every time this loop is run
while (index < 10) {
console.log("The number is " + index);
// this is common shorthand for index = index + 1
index++;
}
The code prints the following output to the terminal:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The most important thing to remember when writing any loop is to always be working towards your condition. In the example above if the code did not increment the index variable by 1 each time the loop ran then it would be stuck with what is called an infinite loop:
let index = 0;
// this is an infinite loop because the condition will never be met
while (index < 10) {
console.log("The number is " + index);
// if you do not increase the index then the condition is never met
// Meaning this will run forever!
}
The above code will run until whatever interpreter you are using crashes:
The number is 0
The number is 0
The number is 0
The number is 0
The number is 0
The number is 0
...continues on forever until interpreter crashes or forcefully quit the process
To exit out of an infinite loop forcefully, press CTRL + C in the terminal that is running the code.
A quick word before you learn about the next loop.
The index is the traditional word for the variable that keeps track of how many times the loop has been run. Don't write loops with indices starting at one; you'll confuse other programmers and yourself. Indices have started at zero for a long time, and for good reason. It's much easier to use loops that start with an index of zero because Array and String indices also start at zero.
let string = "pat";
let index = 0;
while (index < string.length) {
console.log("index: " + index + " ; char: " + string[index]);
index++;
}
The code above will do one loop for each character in the String above. Each of those loops is called an "iteration". An iteration is the act of repeating a procedure, hence looping is an iterative technique. Each repetition itself is also called an "iteration." So you can use loops to iterate through Strings
The code prints the following output to the terminal:
index: 0 ; char: p
index: 1 ; char: a
index: 2 ; char: t
A for loop can be broken down into three sections:
for (<initial expression>;<condition>;<loopEnd expression>)
The for loop is usually used with an integer counter:
for (let index = 0; index < 10; index += 1) {
// the code inside this block will run 10 times
}
While the loopEnd expression is normally used to increase a variable by one per loop iteration, it can contain any statement, such as one that decreases the counter or increases it by 2.
You can use the for loop to iterate through all kinds of things. Check out the example below for how to iterate through a string:
let testString = "testing";
// You can use the testString's length as the condition!
// Since you know the testString's index starts at 0
// and the index starts at 0, you can access each letter:
for (let index = 0; index < testString.length; index += 1) {
let letter = testString[index];
console.log(letter);
}
The code prints the following output to the terminal:
t
e
s
t
i
n
g
These are the most basic types of loops. If all else fails, you can always fall back on these two loops. All the other loop forms are just more convenient forms of these basic loop styles.
So far both while and for loops have been covered. Once you understand the concept of looping, it's easy to translate one loop to another:
// these two functions do the exact same thing!
function commaBetweenEachCharForLoop(str) {
let newStr = "";
// it is convention to shorten index to just i in most cases
for (let i = 0; i < str.length; i++) {
newStr += str[i];
if (i !== str.length - 1) {
newStr += ",";
}
}
return newStr;
};
function commaBetweenEachCharWhileLoop(str) {
let newStr = "";
let i = 0;
while (i < str.length) {
newStr += str[i];
if (i !== str.length - 1) {
newStr += ",";
}
i++;
}
return newStr;
};
console.log(commaBetweenEachCharForLoop('star')); //=> 's,t,a,r'
console.log(commaBetweenEachCharWhileLoop('star')); //=> 's,t,a,r'
What You Learned
You can use a for or while loop to repeat a block of code repeatedly.
While the loop condition is true, the code will execute another iteration of the loop.
Watch out for infinite loop behavior. To exit out of an infinite loop forcefully, press CTRL + C in the terminal that is running the code.
When the loop condition is false, the code will exit the loop.