Mastering the while Loop in JavaScript

📍 What is the while Loop?

The while loop is a control structure that repeatedly executes a block of code as long as a specified condition is true. It's perfect for when the number of iterations isn't known ahead of time. 🌀

>>“Keep going while the condition holds — that's the essence of the while loop.” 🔁

🧪 Syntax

Basic while Loop Syntax

while (condition) {
  // code to run while condition is true
}

The loop checks the condition before each iteration. If it’s true, the block runs. If it’s false, the loop exits. ❌

📘 Example: Counting from 1 to 5

Simple Counter Example

let count = 1;

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

🔹 This prints numbers 1 through 5.
🔹 count++ increases the value each time, avoiding infinite loops. 🧠

⚠️ Infinite Loop Warning

Note

Always make sure the loop condition eventually becomes false. Otherwise, your code could run forever and crash your browser or environment. 😱

❌ Infinite Loop Example

while (true) {
  console.log("This will never stop...");
}

💡 When to Use a while Loop

  • When you don't know how many times to repeat in advance
  • When waiting for a condition to become false
  • When looping based on user input or async conditions

🧠 Real World Use Case

User Input Simulation

let password = "";
const correctPassword = "open123";

while (password !== correctPassword) {
  password = prompt("Enter password:");
}
alert("✅ Access granted!");

Note

In browsers, prompt allows you to simulate user input. This loop keeps asking until the correct password is entered. 🔐

📚 Learn More

>>“A loop is like a heartbeat in code — it runs until it's told to stop.” ❤️