OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 7

Loops: for, while, and do-while

By Ratan Updated: 16 Oct 2026

Repeat code blocks efficiently using standard for loops, while loops, and do-while iterations.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Repeat with a measurable stopping condition

A loop needs an initial state, a condition and progress. for is convenient for counting; while fits a condition whose repetition count is unknown; do-while executes at least once before checking its condition.

let total = 0;
for (let number = 1; number <= 5; number += 1) {
  total += number;
}
console.log(total); // 15

let remaining = 3;
while (remaining > 0) {
  console.log(remaining);
  remaining -= 1;
}

The while example prints 3, 2 and 1. Removing its update creates an infinite loop. A long synchronous loop blocks the browser's main thread, so it can freeze input and rendering even if it eventually terminates.

Array bounds and useful iteration

const marks = [62, 75, 83];
for (let index = 0; index < marks.length; index += 1) {
  console.log(index, marks[index]);
}
for (const mark of marks) {
  console.log(mark);
}

Indices run from zero to length-1. A condition using <= length reads one extra position, normally producing undefined. for...of reads iterable values; for...in enumerates enumerable property keys and is not the ordinary choice for array values.

do-while and flow control

let attempts = 0;
do {
  attempts += 1;
} while (attempts < 1);
console.log(attempts); // 1

break leaves the nearest loop. continue skips to the next iteration. In a while loop, make sure continue cannot bypass the only state update. Avoid mutating an array while traversing it until you understand how that affects the iteration.

Practice and answers

  1. Print even numbers from 2 through 10. Expect 2, 4, 6, 8, 10.
  2. Count multiples of 3 from 1 through 20. Answer: 6.
  3. Find a mark above 80 and break after the first match. The sample match is 83.
  4. Trace the index, current value and accumulator in a small table before running a new loop.

हिन्दी संकेत: हर iteration में condition बदलने की दिशा में progress होना चाहिए; browser को block करने वाले बड़े loops से बचें।

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat