🔁 Loops in JavaScript

Last Updated: 12th October 2025


Loops allow us to repeat a block of code multiple times until a condition is met.
They make our code short, clean, and powerful.

Hinglish Tip 🗣: Loop ka kaam hai — “ek kaam baar-baar karna jab tak condition true ho”.


📌 Why Use Loops?

Without loops 👇

console.log("Hello");
console.log("Hello");
console.log("Hello");
console.log("Hello");
console.log("Hello");

With loops 👇

for (let i = 0; i < 5; i++) {
  console.log("Hello");
}

💡 Less code, same result.


🧭 Types of Loops in JavaScript

Loop TypeUsed When
do...whileWhen you want to execute once before checking condition
whileWhen condition-based repetition is needed
forWhen number of iterations is known
for...ofUsed to loop through iterable items (arrays, strings, etc.)
for...inUsed to loop through object keys

do...while Loop

It will run once, even if the condition is false — because the condition is checked after the loop body.

Syntax:

do {
  // loop body
} while (condition);

Example:

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

💡 Output: Runs once (even though condition is false).


while Loop

Repeats while the condition is true.

Syntax:

while (condition) {
  // loop body
}

Example:

let i = 1;

while (i <= 5) {
  console.log("Count:", i);
  i++;
}

Hinglish Tip 🗣: Jab tak condition true hai, loop chalta rahega.


for Loop

Repeats a specific number of times.

Syntax:

for (initialization; condition; update) {
  // code block
}

Example:

for (let i = 1; i <= 5; i++) {
  console.log("Number:", i);
}

Hinglish Tip 🗣: For loop ek counter jaisa hota hai — start se end tak counting karta hai.


for...of Loop

Used to loop through values in arrays, strings, or other iterables.We don't need to worry about the index,condition, or update.

Syntax:

for (const element of iterable) {
  // code block
}

Example:

let a = "hello world";
for (const char of a) {
  console.log(char);
}

Note : We will see more about for ... of loop in the Arrays section.


for...in Loop

Used to loop through the properties of an object, or the keys of an array, or the indexes of a string.

Syntax:

for (const index in string) {
  // code block
}

Example:

let a = "hello world";
for (const index in a) {
  console.log(index);
}

We will cover more in Objects section.


💡 Quick Practice

  1. Exercises Set 1
  2. Exercises Set 2