JavaScript Looping

Back to JS page

Table of Contents

The for Loop

The for loop repeats a block of code a specific number of times:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Looping</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>The for Loop</h4>
<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 5; i++) {
  text += "Iteration: " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Example 1

Result View Example

The while Loop

The while loop repeats while a condition is true:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Looping</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>The while Loop</h4>
<p id="demo"></p>

<script>
let i = 0;
let text = "";
while (i < 5) {
  text += "Number: " + i + "<br>";
  i++;
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Example 2

Result View Example

The do...while Loop

The do...while loop runs at least once before checking the condition:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Looping</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>The do...while Loop</h4>
<p id="demo"></p>

<script>
let i = 0;
let text = "";
do {
  text += "Number: " + i + "<br>";
  i++;
} while (i < 5);
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Example 3

Result View Example

The for...in Loop

The for...in loop iterates over the keys/properties of an object:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Looping</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>The for...in Loop</h4>
<p id="demo"></p>

<script>
const person = { name: "John", age: 30, city: "New York" };
let text = "";

for (let key in person) {
  text += key + ": " + person[key] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Example 4

Result View Example

The for...of Loop

The for...of loop iterates over the values of an iterable (arrays, strings, Maps, Sets):

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Looping</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>The for...of Loop</h4>
<p id="demo"></p>

<script>
const fruits = ["Apple", "Banana", "Orange"];
let text = "";

for (let fruit of fruits) {
  text += fruit + "<br>";
}

// Can also iterate over strings
text += "<br>String characters:<br>";
for (let ch of "JS") {
  text += ch + " ";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Example 5

Result View Example

Document

Document in project

You can Download PDF file.

Reference