Skip to content

Looping statement in JavaScript with example

  • by

JavaScript offers different types of looping statements to execute a block of code repeatedly based on certain conditions. These are used to execute a block of code repeatedly based on certain conditions.

There are different types of looping statements in JavaScript, including:

  1. for loop
  2. while loop
  3. do-while loop
  4. for...in loop
  5. for...of loop

Looping statement in JavaScript with example

Simple example code.

  1. for loop:

The for loop is used to execute a block of code a fixed number of times.

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

The while loop is used to execute a block of code as long as a condition is true.

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

The do-while loop is used to execute a block of code at least once, and then repeated as long as a condition is true.

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);
  1. for...in loop:

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

<!DOCTYPE html>
<html>
<body>
    <script>
        const person = {
            name: 'John',
            age: 30,
            gender: 'male'
        };

        for (const key in person) {
            console.log(`${key}: ${person[key]}`);
        }

    </script>
</body>
</html>

Output:

Looping statement in JavaScript with example
  1. for...of loop:

The for...of loop is used to iterate over the values of an iterable object (e.g., an array).

const arr = ['apple', 'banana', 'cherry'];

for (const item of arr) {
  console.log(item);
}

Each loop has a different use case and syntax, and this article provides examples for each type to demonstrate how to use them in practice.

Do comment if you have any doubts or suggestions on this Js basic topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading