Skip to main content

Loops

A common programming task is to perform similar actions a number of times. For example, displaying clients from the list one by one, or iterating over salaries and executing the same code for each. It is for such purposes, i.e. multiple repetition of one piece of code, that loops are used.

  • Loop is a control structure in high-level programming languages, designed for the repeated execution of a set of statements.
  • Loop body is a sequence of statements intended for repeated execution.
  • Iteration is single execution of the loop body.
  • Exit condition is an expression that determines whether the iteration will be executed again or the loop will end.
  • Counter is a variable storing the current iteration number. The loop does not necessarily contain a counter, and it does not have to be one; the loop exit condition may depend on several variables to be changed in the loop.

while loop

Pre-test loop is a loop that is executed as long as a condition specified before its beginning stays true. This condition is checked before the loop body is executed, which is why the body may not be executed even once if the condition is false at the very beginning.

while (condition) {
// code, loop body (statement)
}

The while construct creates a loop that executes a block of code as long as the test condition evaluates to true.

  • condition is evaluated before each iteration of the loop.
  • If condition evaluates to true, the while statement executes statement.
  • If condition evaluates to false, the loop is no longer executed, and the script continues to execute statements after the while loop.

This flowchart illustrates the while loop.

while loop

Let's make a counter.

let counter = 0;

while (counter < 10) {
console.log("counter: ", counter);
counter += 1;
}

Fill rooms in the hotel until the current number of clients is equal to the maximum allowed.

let clientCounter = 18;
const maxClients = 25;

while (clientCounter < maxClients) {
console.log(clientCounter);
clientCounter += 1;
}

do...while loop

Post-test loop is a loop in which the condition is tested after executing the loop body. Hence, the body is executed at least once.

do {
// statement
} while (condition);

The do...while construct creates a loop that executes a block of code unless condition returns false.

Unlike the while loop, the do...while loop executes statement at least once before it evaluates condition.

Inside the loop, you need to make changes to a variable to make sure that the expression evaluates to false after some iterations. Otherwise, there will be an endless loop.

This flowchart illustrates the do-while loop.

do...while loop
let password = "";

do {
password = prompt("Enter a password longer than 4 characters", "");
} while (password.length < 5);

console.log("Entered password: ", password);

for loop

*Count-controlled loop is a loop in which a variable changes its value from a set initial value to an end value with a step, and for each value of this variable the loop body is executed once.

In most procedural programming languages, it is implemented with the for construct, which specifies the counter, the required number of iterations and the counting step.

for (initialization; condition; post-expression) {
// statements
}

for loop: execution algorithm:

  • Initialization is executed once before the loop starts. It is used to create a counter variable and specify its initial value.
  • Condition is an expression that is evaluated before each iteration of the loop. The loop body is executed only when the expression can be converted to true. The loop ends when the value is false.
  • Statements are a set of statements to execute on each repetition. They are executed if the condition expression is converted to true.
  • Post-expression is executed at the end of each iteration of the loop, before testing the condition. It is used to update the counter variable.

Counter variables are traditionally called i, j and k.

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

In the example, the counter variable i is declared, initialized with 0, and the loop is executed until i <= 20, that is, the condition is converted to true. After each iteration, the counter is incremented by 5.

Calculate the sum of numbers up to a certain value.

const target = 3;
let sum = 0;

for (let i = 0; i <= target; i += 1) {
sum += i;
}

console.log(sum);

Call to mind the a % b operation and find the remainder of division using a loop.

const max = 10;
for (let i = 0; i < max; i += 1) {
console.log(`${max} % ${i} = `, max % i);
}

break operator

You can interrupt the execution of a loop at any time. For this purpose, there is a break operator, which completely terminates the execution of the loop and transfers control to the string after its body.

Find the number 3. As soon as the if condition is met, the loop will stop executing (it will be interrupted).

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

if (i === 3) {
console.log("Number 3 found, abort the loop");
break;
}
}

console.log("Log after loop");

continue operator

It does not interrupt the entire loop, but only the current iteration. It is used when there is nothing else to do in the current iteration, or nothing needs to be done at all, and it is time to move on to the next iteration.

Use a loop for odd numbers only. For even i, continue is triggered, execution of the body is terminated and control is transferred to the next iteration.

const number = 10;

for (let i = 0; i < number; i += 1) {
if (i % 2 === 0) {
continue;
}

console.log("Odd i: ", i); // 1, 3, 5, 7, 9
}