Skip to content

JavaScript iteration

  • by

JavaScript iteration refers to the process of repeating a set of instructions multiple times. In JavaScript, there are several ways you can do iteration on the sequence data structure using for loops, while loops, and do-while loops.

JavaScript iteration example

Simple example code iterate through an array of numbers and print each one to the console.

For-in loop:

<!DOCTYPE html>
<html>
<body>
<script>
    let numbers = [1, 2, 3, 4, 5];

    for (let i = 0; i < numbers.length; i++) {
    console.log(i + " index value->", numbers[i]);
    }

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

Output:

JavaScript iteration

While loop:

let i = 0;

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

Do-while loop:

let i = 0;

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

Use a for-in loop to iterate through the properties of an object called person and print their values to the console.

let person = {
  name: "John",
  age: 30,
  occupation: "Engineer"
};

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

Output:

name: John
age: 30
occupation: Engineer

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

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

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

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

Continue reading