For, While and Do While LOOP in JavaScript with Example

⚡ Smart Summary

For, While and Do While loops in JavaScript repeat a block of statements without duplicating code. This article explains each syntax, shows runnable examples with expected output, adds the for-in and for-of forms, and covers break, continue, and infinite loop prevention.

  • 🔁 Core Purpose: A loop executes the same statements repeatedly for a fixed count or while a stated condition remains true.
  • 🔢 for Loop: Three expressions in the header handle initialisation, the exit test, and the update, which suits a known iteration count.
  • while Loop: The condition is tested before every pass, so the body may never execute if the condition starts false.
  • 1️⃣ do…while Loop: The body always runs at least once because the condition is evaluated after the first pass.
  • 🔑 for…in Loop: Iterates over the keys of an object, returning property names rather than values.
  • 📦 for…of Loop: Iterates over the values of arrays, strings, maps, and other iterable objects.
  • Flow Control: The break statement exits a loop immediately, while continue skips to the next iteration.

For While and Do While Loop in JavaScript

What is a Loop in JavaScript?

Loops are useful when you have to execute the same lines of code repeatedly, for a specific number of times or as long as a specific condition is true. Suppose you want to type a ‘Hello’ message 100 times in your webpage. Of course, you will have to copy and paste the same line 100 times. Instead, if you use loops, you can complete this task in just 3 or 4 lines.

Every loop is built from the same three parts, whatever the syntax looks like: a starting value, a condition that decides whether another pass runs, and an update that moves the loop towards its exit. The diagram below shows that repeating cycle.

Use Loops in Javascript

Different Types of Loops in JavaScript

There are mainly four types of loops in JavaScript.

  1. for loop
  2. for/in loop
  3. while loop
  4. do…while loop

Modern JavaScript adds the for…of loop for iterating values directly, so five forms are available in practice. The table below shows which one to reach for in a given situation.

Loop Condition Checked Minimum Executions Best Used For
for Before each pass 0 A known number of repetitions
while Before each pass 0 An unknown count driven by a condition
do…while After each pass 1 Menus and prompts that must run once
for…in Before each pass 0 Reading the keys of an object
for…of Before each pass 0 Reading the values of an array or string

for loop

Syntax:

for(statement1; statement2; statment3)
{
lines of code to be executed
}
  1. The statement1 is executed first, even before executing the looping code. So, this statement is normally used to assign values to variables that will be used inside the loop.
  2. The statement2 is the condition to execute the loop.
  3. The statement3 is executed every time after the looping code is executed.

Try this yourself:

<html>
<head>
	<script type="text/javascript">
		var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth");
		document.write("<b>Using for loops </b><br />");
		for (i=0;i<students.length;i++)
		{
		document.write(students[i] + "<br />");
		}
	</script>
</head>
<body>
</body>
</html>

Output:

Using for loops
John
Ann
Aaron
Edwin
Elizabeth

The counter starts at 0 because the first index of an array is zero, and the condition uses students.length so the loop adapts automatically when names are added or removed.

while loop

Syntax:

while(condition)
{
lines of code to be executed
}

The “while loop” is executed as long as the specified condition is true. Inside the while loop, you should include the statement that will end the loop at some point of time. Otherwise, your loop will never end and your browser may crash.

Try this yourself:

<html>
<head>
	<script type="text/javascript">
		document.write("<b>Using while loops </b><br />");
		var i = 0, j = 1, k;
		document.write("Fibonacci series less than 40<br />");
		while(i<40)
		{
			document.write(i + "<br />");
			k = i+j;
			i = j;
			j = k;
		}
	</script>
</head>
<body>
</body>
</html>

Output:

Using while loops
Fibonacci series less than 40
0
1
1
2
3
5
8
13
21
34

⚠️ Warning: A while loop whose condition never becomes false freezes the browser tab. Always confirm that a variable inside the body moves the condition towards false, and use a safety counter when the exit depends on external data.

do…while loop

Syntax:

do
{
block of code to be executed
} while (condition)

The do…while loop is very similar to the while loop. The only difference is that in the do…while loop, the block of code gets executed once even before checking the condition.

Try this yourself:

<html>
<head>
	<script type="text/javascript">
		document.write("<b>Using do...while loops </b><br />");
		var i = 2;
		document.write("Even numbers less than 20<br />");
		do
		{
			document.write(i + "<br />");
			i = i + 2;
		}while(i<20)
	</script>
</head>
<body>
</body>
</html>

Output:

Using do...while loops
Even numbers less than 20
2
4
6
8
10
12
14
16
18

The difference becomes visible when the condition is false from the start. A while loop prints nothing, whereas a do…while loop still prints one line before stopping.

for…in loop

The for…in loop walks through the enumerable property names of an object. Each pass assigns the next key to the loop variable, and the value is read with bracket notation.

const student = {
    name: "Ann",
    age: 21,
    course: "JavaScript"
};

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

Output:

name : Ann
age : 21
course : JavaScript

💡 Tip: Avoid for…in on arrays. It returns index values as strings and also visits inherited properties, which can produce surprising results. Use for…of or a classic for loop for arrays instead.

for…of loop and forEach

The for…of loop reads the values of any iterable object, including arrays, strings, maps, and sets. The forEach method achieves the same result with a callback function and gives access to the index.

const students = ["John", "Ann", "Aaron"];

// for...of reads each value directly
for (const name of students) {
    console.log(name);
}

// forEach supplies the value and the index
students.forEach(function (name, index) {
    console.log(index + " - " + name);
});

// strings are iterable too
for (const letter of "Ann") {
    console.log(letter);
}

Output:

John
Ann
Aaron
0 - John
1 - Ann
2 - Aaron
A
n
n

One practical difference matters: break and continue work inside for…of, but they cannot be used inside forEach, because each callback is a separate function.

break and continue Statements

Two keywords change the normal flow of any loop. The break statement leaves the loop entirely, and the continue statement abandons the current pass and jumps to the next one.

const numbers = [4, 7, 10, 13, 16, 19];

// continue: skip odd numbers
for (const n of numbers) {
    if (n % 2 !== 0) {
        continue;
    }
    console.log("even: " + n);
}

// break: stop at the first value above 12
for (const n of numbers) {
    if (n > 12) {
        console.log("first value above 12: " + n);
        break;
    }
}

Output:

even: 4
even: 10
even: 16
first value above 12: 13

Loops appear in nearly every script you will write. Continue with the practical JavaScript code examples, revisit JavaScript array methods for the iteration helpers built on top of these loops, and read internal and external JavaScript to decide where the finished script should live.

FAQs

A while loop tests the condition before the first pass, so the body may never run. A do…while loop tests afterwards, which guarantees at least one execution of the block.

Yes. An inner loop completes every pass for each single pass of the outer loop, which is how grids and tables are built. Use different counter names to avoid overwriting the outer index.

Close the affected tab, then correct the condition or the update statement before reloading. Adding a counter that breaks after a maximum number of passes prevents a repeat during development.

The classic for loop is marginally fastest on large arrays because it avoids callback overhead. The difference is negligible below a few thousand items, so favour readability instead.

They usually default to for…of or map. Review the suggestion when the task needs an index, an early exit, or a guaranteed first pass, since those cases call for a different form.

A for await…of loop reads chunks from a streamed response and appends each token to the page. It is the asynchronous counterpart of for…of and requires an async function.

Summarize this post with: