JavaScript Loops β€” for, while, do...while

Himmat Kumar Jun 1, 2025, 1:17 AM
Blog Thumbnail

πŸ” JavaScript Loops β€” Made Easy (and Real!)

Ever find yourself copying and pasting the same line of code over and over? Loops are here to save your fingers (and your sanity). In JavaScript, loops let you repeat a block of code without writing it multiple times. Think of them like a playlist on repeat β€” you set it once, and it keeps going.

πŸ”Ή for Loop β€” When You Know How Many Times

Use a for loop if you know how many times something should repeat. Here’s an example:

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

This prints:

Step 1
Step 2
Step 3
Step 4
Step 5

It’s like saying, β€œHey JavaScript, do this 5 times, please.”

πŸ”Ή while Loop β€” When You’re Not Sure Yet

If you’re not certain how many times the code should run, but you want it to keep going while a condition is true, then go for a while loop.

let count = 1;

while (count <= 3) {
  console.log("Count is: " + count);
  count++;
}

Here, the loop checks the condition first. If it’s true, it runs the block. If not, it skips it.

πŸ”Ή do...while Loop β€” Run At Least Once

This one guarantees at least one run β€” even if the condition is false. It’s great when you want something to happen first, then decide whether to keep going.

let number = 1;

do {
  console.log("Number is: " + number);
  number++;
} while (number <= 2);

Even if the condition fails after the first run, the block still executes once.

πŸ”„ TL;DR β€” Loop Logic Recap

  • for – Use when you know how many times you want to loop.
  • while – Use when you want to loop while a condition is true.
  • do...while – Use when you need to run first, check later.
πŸ’‘ Pro Tip: Always make sure your condition will become false at some point β€” or your code might end up in an endless loop!

Related Posts

Himmat Kumar β€’ Jun 1, 2025, 12:57 AM

Date and Time in JavaScript β€” Easy Guide

Himmat Kumar β€’ May 31, 2025, 7:47 PM

Difference between javascript and jquery with examples

Himmat Kumar β€’ May 31, 2025, 7:47 PM

JavaScript Variables: var vs let vs const

Himmat Kumar β€’ May 31, 2025, 7:47 PM

JavaScript Data Types Explained with Examples

Himmat Kumar β€’ May 31, 2025, 7:47 PM

JavaScript Functions & Scope

Himmat Kumar β€’ May 31, 2025, 7:47 PM

Introduction JavaScript

112 viewsLaravel
Himmat Kumar β€’ Jun 1, 2025, 12:53 AM

Master Laravel: Basic System Requirement,Installation a...