For in JavaScript

JavaScript provides several ways to create loops. Here are some basic types of loops.

// The most basic type, with a single condition.
let i = 1;
while (i <= 3) {
    console.log(i);
    i = i + 1;
}

// A classic initial/condition/after for loop.
for (let j = 0; j < 3; j++) {
    console.log(j);
}

// Another way of accomplishing the basic "do this
// N times" iteration is using Array.from().
Array.from({length: 3}, (_, i) => {
    console.log("range", i);
});

// A loop without a condition will run repeatedly
// until you break out of the loop or return from
// the enclosing function.
while (true) {
    console.log("loop");
    break;
}

// You can also continue to the next iteration of
// the loop.
for (let n = 0; n < 6; n++) {
    if (n % 2 === 0) {
        continue;
    }
    console.log(n);
}

When you run this script, you’ll see the following output:

1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

JavaScript provides other looping constructs as well, such as for...of for iterating over iterable objects, and for...in for enumerating object properties. We’ll see some of these forms later when we look at arrays, objects, and other data structures.