Skip to content

Loops in JavaScript

For loop

for loop: This is a control flow statement that allows code to be executed repeatedly. A for loop is made up of four parts: initialization, condition, final-expression, and statement.

for (initialization; condition; final-expression) {
    // statement
}

Here’s an example:

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

For-In loop (through objects)

for-in loop: The for-in loop is used to loop through the properties of an object.

for (variable in object) {
    // statement
}

Here’s an example:

let person = {firstName:"John", lastName:"Doe", age:25};

for (let key in person) {
    console.log(key + ": " + person[key]);
}

For-Of loops (through iterables)

  1. for-of loop: The for-of loop is used to loop over iterable objects, like arrays and strings.
for (variable of iterable) {
    // statement
}

Here’s an example:

let arr = [3, 5, 7];

for (let value of arr) {
    console.log(value);
}

While loop

while loop: A while loop executes its statements as long as a specified condition evaluates to true.

while (condition) {
    // statement
}

Here’s an example:

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

Do-While loop

do-while loop: The do-while loop is similar to the while loop, except that the condition is tested at the end of the loop, so the loop will always be executed at least once.

do {
    // statement
} while (condition);

Here’s an example:

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