while loops
The first loop we will discuss is the while loop. A while loop executes a certain block of code as long as an expression evaluates to true. The snippet below demonstrates the syntax of the while loop:
while (condition) {
// code that gets executed as long as the condition is true
}
The while loop will only be executed as long as the condition is true, so if the condition is false to begin with, the code inside will be skipped.
Here is a very simple example of a while loop printing the numbers 0 to 10 (excluding 10) to the console:
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
The output will be as follows:
1
2
3
4
5
6
7
8
9
These are the steps happening here:
- Create a variable,
i, and set its value to zero - Start the
whileloop and check the condition that the value ofiis smaller than 10 - Since the condition is true, the code logs
iand increasesiby 1 - The condition gets evaluated again; 1 is still...