zhaoJian's Tech Notes

IT Course JavaScript Basics 042_Loops while, for

Learning / JavaScript Basics ~6309 words · 16 min read - views

Loop statements are methods for repeatedly executing a code block. JavaScript provides different types of loop statements such as while, do-while, and for. A complete loop body includes: initialization expression, loop condition, and iterator.

while Loop

The while loop is used to repeatedly execute a piece of code while the condition is true. A single execution of the loop body is called one iteration. Any expression or variable can be a loop condition. The loop condition is evaluated and the result is converted to a boolean value. Similar to if, if the loop body has only one statement, you can omit the curly braces {…}, but this is not recommended. The condition is checked before each iteration.

Example:

let i = 0; // Initialization expression, usually used to declare counter variable, will error undefined if missing
while (i < 5) { // Loop condition, when `true`, the loop will keep executing
console.log(i);
i++; // Iterator, usually used to update counter variable to match loop condition
}

Infinite loop example:

let i = 0;
while (1) { // Condition always true will enter infinite loop
console.log(i);
i++; // Usually use this form of counter to update loop condition
if (i >= 5) break; // Comment out to enter infinite loop mode
}

do-while Loop

The do-while loop is similar to the while loop, but it first executes the loop body once, then checks if the condition is true. If the condition is true, it continues to execute the loop body. Pay attention to the use case - only use do-while when the loop body needs to be executed at least once regardless of whether the condition is true. For other scenarios, while loop is recommended. The condition is checked after each iteration.

Example:

let i = 0;
do {
console.log(i);
i++;
} while (i < 5);

for Loop

The for loop is a more complex but most commonly used loop structure for repeatedly executing a piece of code. The for loop contains three parts: initialization expression, loop condition, and iterator. Here is the basic syntax of the for loop: The condition is checked before each iteration, and other settings can be used.

Example:

for (let i = 0; i < 5; i++) {
console.log(i);
}

Infinite loop example:

let i = 0;
for ( ; ; ) { // Omitting all conditions will enter infinite loop
console.log(i);
i++; // Usually use this form of counter to update loop condition
if (i >= 5) break; // Comment out to enter infinite loop mode
}
Omitting Statement Segments

The for loop can omit any one or more of the initialization expression, loop condition, or iterator, but the semicolons ; must be retained. Semicolons are used to separate each part, and when omitting one part, the corresponding semicolon still needs to be retained.

Example:

let x = 0;
for (; x < 5; x++) {
console.log(x);
}
// Omitting initialization expression, moving it outside the loop, the loop is still valid
let y = 0;
for (;; y++) {
if (y >= 5) {
break;
}
console.log(y);
}
// Omitting loop condition, using `if` statement and `break` to terminate the loop
let z = 0;
for (; z < 5;) {
console.log(z);
z++;
}
// Omitting iterator, iterator is moved inside the loop body, the loop is still valid

Nested Loops

Nested loops refer to containing another complete loop structure within a loop body. Nested loops execute the inner loop once each time the outer loop executes.

Right triangle example:

// Example A
for (let i = 1; i <= 5; i++) { // Outer loop, controls row count, from 1 to 5.
let row = ''; // Each time the outer loop executes, create an empty string `row` to store stars for current row.
for (let j = 1; j <= i; j++) { // Inner loop, controls number of stars per row, from 1 to current row number `i`.
row += ''; // Append star to `row`, forming the star string for current row.
}
console.log(row); // Output the star string for current row.
}
// Example B
for (let i = 1; i <= 5; i++) { // Outer loop represents row count
for (let j = 1; j <= i; j++) { // Inner loop represents columns
document.write(''); // Use star as graphic element
}
document.write('</br>'); // Line break
}

Inverted triangle example:

// Example A
for (let i = 5; i >= 1; i--) { // Outer loop, controls row count, from 1 to 5.
let row = ''; // Each time the outer loop executes, create an empty string `row` to store stars for current row.
for (let j = 1; j <= i; j++) { // Inner loop, controls number of stars per row, from 1 to current row number `i`.
row += '* '; // Append star to `row`, forming the star string for current row.
}
console.log(row); // Output the star string for current row.
}
// Example B
for (let i = 1; i <= 5; i++) { // Outer loop represents row count
for (let j = 0; j <= 5 - i; j++) { // Inner loop represents columns
document.write(''); // Use star as graphic element
}
document.write('</br>'); // Line break
}

break Terminates (Ends, Exits) Loop

break is used to terminate (end, exit) the current loop or switch statement. If there is no break, subsequent case statements will continue to execute (i.e., “fall-through” occurs).

The combination of “infinite loop + break” is suitable for situations where you don’t need to check conditions at the beginning/end of the loop, but need to check conditions at multiple positions in the middle or even in the body.

Example:

let count = 0;
while (true) {
console.log("Looping...");
// Simulate a condition, exit loop when satisfied
if (count === 5) {
console.log("Condition met, exiting loop");
break;
}
count++;
}

continue Continues to Next (Skips) Iteration

continue is used to end the current iteration early in a loop and continue to the next iteration. continue is a “lightweight version” of break. It doesn’t stop the entire loop, but stops the current iteration and forces a new round of loop to start (if conditions allow).

Example:

for (let i = 0; i < 8; i++) {
if (i % 2 === 0) {
continue; // Skip current iteration when i modulo 2 equals 0, continue to next iteration
}
console.log(i);
}
Share:

Comments