Repetition processing in JavaScript

Repetition processing in JavaScript

In this article, we will explain repetition processing in JavaScript.

YouTube Video

The for statement in JavaScript

Basic Syntax

1for (initialization; condition; update) {
2  // Code to repeat
3}

The for statement in JavaScript is a syntax for performing iteration. It repeatedly executes a specified block of code as long as a particular condition is met. By using the for statement, the same process can be executed efficiently multiple times.

  • Initialization (initialization): The part that is executed only once before starting the loop. Initialize variables such as the loop counter.
  • Condition (condition): The condition that determines whether to continue the loop. If true, the loop continues; if false, it ends.
  • Update (update): This is executed at the end of each loop to update the loop counter.

Example

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

In this case, i starts at 0, and the loop runs as long as i < 5 is true. i++ increments i by 1 on each iteration of the loop. As a result, numbers from 0 to 4 are displayed.

Scope of the Loop Counter

Declare or initialize variables in the initialization part of the for statement. Variables declared here are only valid within the loop.

1for (let i = 0; i < 3; i++) {
2    console.log(i); // Outputs 0, 1, 2
3}
4console.log(i);  // ReferenceError
  • As shown in this example, referencing a variable outside the for statement will result in an error.

Infinite Loop

Setting a condition that does not end the loop results in an infinite loop. This might put a strain on the browser or system, so caution is needed.

1for (;;) {
2    console.log("Infinite loop");
3    break; // Exits the infinite loop with break
4}

Arrays and the for Statement

It is common to use the for statement in conjunction with arrays. It is convenient for processing each element of an array.

Example

1let fruits = ["apple", "banana", "cherry"];
2
3for (let i = 0; i < fruits.length; i++) {
4    console.log(fruits[i]);
5}
6// Outputs "apple", "banana", "cherry"

This way, you can process each element of an array using indices.

Other Loop Constructs

for...of Statement

The for...of statement is used for iterable objects like arrays and strings.

1let fruits = ["apple", "banana", "cherry"];
2
3for (let fruit of fruits) {
4    console.log(fruit);
5}
6// Outputs "apple", "banana", "cherry"

This allows you to process each element without using indices.

for...in Statement

for...in statement is used to iterate over the properties of an object.

1let person = { name: "John", age: 30, city: "Tokyo" };
2
3for (let key in person) {
4    console.log(key + ": " + person[key]);
5}
6// Outputs "name: John", "age: 30", "city: Tokyo"

In this way, you can perform operations on each element using the keys.

Summary

  • The for statement is a loop construct with three parts: initialization, condition, and update.
  • You can control the behavior of loops using break or continue.
  • When combined with arrays or objects, elements or properties can be processed efficiently.

The while Statement in JavaScript

Basic Syntax

1while (condition) {
2    // Code that repeats while the condition is true
3}

The while statement in JavaScript is a loop structure that executes repeated operations as long as the specified condition is true. Similar to the for statement, the while statement only specifies the condition.

  • Condition: Write the conditional expression that determines whether to continue the loop. The loop continues while true and ends when it becomes false.

Example

1let i = 0;
2
3while (i < 5) {
4    console.log(i);
5    i++;
6}
7console.log(i);  // 5

In this example, the loop starts with the variable i at 0 and executes as long as i < 5 is true. In each loop iteration, i is increased by 1, and when i becomes 5, the condition becomes false and the loop ends. As a result, the while statement displays from 0 to 4.

Unlike the for statement, in the while statement, initialization and update of variables are written as separate statements. You can also refer to the variable after the while statement. In this case, 5 is displayed after the while statement has ended.

Infinite Loop

If the condition is always true, an infinite loop occurs that does not end. Infinite loops should be avoided, but if used intentionally, you can terminate the loop with a break statement.

Example

1while (true) {
2    console.log("Infinite loop");
3    break;  // Ends the loop with `break`
4}

Processing Arrays with a while Loop

It is also possible to process arrays with a while statement.

Example

1let fruits = ["apple", "banana", "cherry"];
2let i = 0;
3
4while (i < fruits.length) {
5    console.log(fruits[i]);
6    i++;
7}
8// Outputs "apple", "banana", "cherry"

do...while Statement

Basic Syntax

1do {
2    // Code that is executed at least once
3} while (condition);

The do...while statement, a variant of the while statement, checks the condition after executing the loop at least once. While the while statement checks the condition first, the do...while statement executes the process once before verifying the condition.

Example

1let i = 0;
2
3do {
4    console.log(i);
5    i++;
6} while (i < 5);

In this example, i is displayed from 0 to 4. The do...while statement differs from the while statement in that it is always executed once, even if the condition is false.

Summary

  • The while statement is used to repeatedly execute code as long as the condition is true.
  • Be cautious of infinite loops, but you can control the flow of loops using break and continue.
  • The do...while statement is useful when you want to execute the loop at least once.

break and continue

You can use break and continue inside the loop.

  • break is used to terminate the loop prematurely.
  • continue skips the current iteration and proceeds to the next iteration.

Example of break

 1for (let i = 0; i < 10; i++) {
 2    if (i === 5) {
 3        break;  // Exits the loop when i is 5
 4    }
 5    console.log(i);
 6}
 7// Outputs 0, 1, 2, 3, 4
 8
 9let i = 0;
10
11while (i < 10) {
12    if (i === 5) {
13        break;  // Ends the loop when i is 5
14    }
15    console.log(i++);
16}
17// Outputs 0, 1, 2, 3, 4

In this case, break is executed when i becomes 5. As a result, numbers from 0 to 4 are displayed.

Example of continue

 1for (let i = 0; i < 5; i++) {
 2    if (i === 2) {
 3        continue;  // Skips when i is 2
 4    }
 5    console.log(i);
 6}
 7// Outputs 0, 1, 3, 4
 8
 9let i = 0;
10while (i < 5) {
11    i++;
12    if (i === 2) {
13        continue;  // Skips when i is 2
14    }
15    console.log(i);
16}
17// Outputs 0, 1, 3, 4

In this case, continue is executed when i is 2. As a result, numbers other than 2 are displayed.

Nested Loops in JavaScript

In JavaScript programming, a nested loop is a structure where one loop exists inside another. Such loops are very effective when specific algorithms or processes span multiple dimensions or layers. For example, processing a multidimensional array with arrays within arrays is a typical case.

Here, we will explain the basic structure of nested loops, usage examples, precautions, and optimization considerations.

Basic Structure of Nested Loops

The basic structure of a nested loop is a form where one or more loops are contained within another loop. Every time the outer loop is executed once, the inner loop is executed that many times.

Below is a basic example of two nested loops.

 1for (let i = 0; i < 3; i++) {
 2    console.log(`Outer loop iteration: ${i}`);
 3
 4    for (let j = 0; j < 2; j++) {
 5        console.log(`  Inner loop iteration: ${j}`);
 6    }
 7}
 8// Output:
 9// Outer loop iteration: 0
10//   Inner loop iteration: 0
11//   Inner loop iteration: 1
12// Outer loop iteration: 1
13//   Inner loop iteration: 0
14//   Inner loop iteration: 1
15// Outer loop iteration: 2
16//   Inner loop iteration: 0
17//   Inner loop iteration: 1

In the above code, i is counted in the outer loop, and j is counted in the inner loop. Every time the outer loop is executed once, the inner loop is executed twice.

Practical Example of Nested Loops

Nested loops are particularly useful for handling multidimensional arrays. For example, when processing a two-dimensional array, you need to handle both the rows (outer loop) and columns (inner loop).

In the following example, we handle a two-dimensional array and print each element.

 1const matrix = [
 2  [1, 2, 3],
 3  [4, 5, 6],
 4  [7, 8, 9]
 5];
 6
 7for (let row = 0; row < matrix.length; row++) {
 8    for (let col = 0; col < matrix[row].length; col++) {
 9        console.log(`Element at [${row}][${col}] is: ${matrix[row][col]}`);
10    }
11}
12// Output:
13// Element at [0][0] is: 1
14// Element at [0][1] is: 2
15// Element at [0][2] is: 3
16// Element at [1][0] is: 4
17// Element at [1][1] is: 5
18// Element at [1][2] is: 6
19// Element at [2][0] is: 7
20// Element at [2][1] is: 8
21// Element at [2][2] is: 9

In this way, using nested loops allows access to each element of a two-dimensional array.

Notes

There are some points to be aware of when using nested loops.

  1. Performance Issues

    As nested loops get deeper, execution time increases sharply. For example, if the outer loop is executed 100 times and the inner loop 100 times, a total of 10,000 operations are performed. Therefore, if there are many loop iterations, you should consider loop optimization for efficiency.

  2. Application to Complex Algorithms

    Nested loops are very powerful, but as processing becomes complex, the code can become difficult to understand. Therefore, to maintain code readability, it is important to organize processing with appropriate comments and functions.

Optimization Considerations

When using nested loops, the following optimizations can be considered.

  1. Early Loop Termination

    If a specific condition is met inside the loop, you can use a break statement to exit the loop. This can avoid unnecessary loops and improve performance.

1for (let i = 0; i < 5; i++) {
2    for (let j = 0; j < 5; j++) {
3        if (i + j > 5) {
4            break;
5        }
6        console.log(`i: ${i}, j: ${j}`);
7    }
8}
  1. Move Calculations Outside

    Instead of performing the same calculation inside the loop each time, you can perform it once outside the loop and use the result to make the process more efficient.

 1let array = [1, 2, 3, 4, 5];
 2
 3// Inefficient example (calculating every time)
 4for (let i = 0; i < array.length; i++) {
 5    for (let j = 0; j < array.length; j++) {
 6        let sum = array[i] + array[j];
 7        console.log(sum);
 8    }
 9}
10
11// Efficient example (calculating outside)
12let arrayLength = array.length;
13for (let i = 0; i < arrayLength; i++) {
14    for (let j = 0; j < arrayLength; j++) {
15        let sum = array[i] + array[j];
16        console.log(sum);
17    }
18}

Summary

Nested loops are very useful for handling complex data structures and algorithms in JavaScript. However, if not used properly, they can lead to performance degradation and reduced code readability. To use nested loops effectively, it is important to strive for loop optimization and code organization, and to take appropriate approaches depending on the situation.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video