Skip to content
On this page

Looping

To calculate (1 + 2 + 3), we can directly write the expression:

javascript
1 + 2 + 3; // 6

To calculate (1 + 2 + 3 + ... + 10), we can manage it. However, for (1 + 2 + 3 + ... + 10000), writing it out directly is impractical.

For computing thousands of repetitive calculations, we need loop statements. JavaScript has two types of loops: the for loop, which executes a block of statements based on an initial condition, end condition, and increment condition:

javascript
let x = 0;
let i;
for (i = 1; i <= 10000; i++) {
    x = x + i;
}
x; // 50005000

Let's analyze the control conditions of the for loop:

  • i=1: This is the initial condition, setting i to 1.
  • i<=10000: This is the condition check; it continues the loop while true.
  • i++: This is the increment condition; i increases by 1 after each loop iteration, eventually causing it to not satisfy i <= 10000 and exit.

Exercise

Use a for loop to calculate the result of (1 \times 2 \times 3 \times ... \times 10):

javascript
let x = ?;
let i;
for ...

if (x === 3628800) {
    console.log('1 x 2 x 3 x ... x 10 = ' + x);
} else {
    console.log('Calculation error');
}

The for loop is commonly used to iterate over arrays using an index:

javascript
let arr = ['Apple', 'Google', 'Microsoft'];
let i, x;
for (i = 0; i < arr.length; i++) {
    x = arr[i];
    console.log(x);
}

All three conditions of a for loop can be omitted. If there is no exit condition, you must use the break statement to exit the loop; otherwise, it becomes an infinite loop:

javascript
let x = 0;
for (;;) { // This will loop indefinitely
    if (x > 100) {
        break; // Exit the loop via if statement
    }
    x++;
}

for ... in

A variant of the for loop is for ... in, which can iterate over all properties of an object:

javascript
let o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (let key in o) {
    console.log(key); // 'name', 'age', 'city'
}

To filter out inherited properties, use hasOwnProperty():

javascript
let o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (let key in o) {
    if (o.hasOwnProperty(key)) {
        console.log(key); // 'name', 'age', 'city'
    }
}

Since arrays are also objects, and their elements' indices are treated as object properties, the for ... in loop can directly loop through an array's indices:

javascript
let a = ['A', 'B', 'C'];
for (let i in a) {
    console.log(i); // '0', '1', '2'
    console.log(a[i]); // 'A', 'B', 'C'
}

Note that for ... in iterates over array indices as strings, not numbers.

while

The for loop is useful when initial and end conditions are known. However, for loops that ignore conditions can obscure the loop logic, making while loops more suitable. A while loop has only one condition; while it's true, it continues looping:

javascript
let x = 0;
let n = 99;
while (n > 0) {
    x = x + n;
    n = n - 2;
}
x; // 2500

Within the loop, n decreases until it becomes -1, at which point it no longer satisfies the while condition, causing the loop to exit.

do ... while

The final type of loop is do { ... } while(), which checks the condition after each iteration:

javascript
let n = 0;
do {
    n = n + 1;
} while (n < 100);
n; // 100

Using do { ... } while() ensures the loop body executes at least once, unlike for and while, which may not execute at all.

Exercise

Use a loop to iterate through each name in the array and display "Hello, xxx!":

javascript
let arr = ['Bart', 'Lisa', 'Adam'];

for ...

Summary

Loops are an effective way for computers to perform repetitive tasks. Poorly written loop code can lead to "infinite loops," causing browsers to become unresponsive or crash. Always pay close attention to initial and condition checks in loop code, especially at boundary values. Notably, i < 100 and i <= 100 represent different logical conditions.

Looping has loaded