JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Loop While


📘 JavaScript while Loop – Repeat While a Condition is True

The while loop continues to execute a block of code as long as the specified condition evaluates to true.


🔹 Syntax

while (condition) {
  // code block to be executed
}
  • condition is evaluated before each iteration.

  • If it returns true, the code inside the loop runs.

  • When the condition becomes false, the loop stops.


🔹 Basic Example

let i = 1;

while (i <= 5) {
  console.log(i);
  i++;
}
// Output: 1 2 3 4 5

🔹 Infinite Loop Warning

If you forget to update the loop variable (like i++), the condition may never become false, causing an infinite loop.

let i = 1;

while (i <= 5) {
  console.log(i);
  // missing i++
}

🚨 Always ensure your loop has a way to exit.


🔹 Using break and continue

let i = 1;

while (i <= 5) {
  if (i === 3) {
    i++;
    continue;
  }
  console.log(i);
  i++;
}
// Output: 1 2 4 5
let j = 1;

while (j <= 5) {
  if (j === 4) break;
  console.log(j);
  j++;
}
// Output: 1 2 3

Practice Questions

Q1. What is the syntax of a while loop in JavaScript?

Q2. How do you use a while loop to print numbers from 1 to 10?

Q3. How can you avoid an infinite while loop in your code?

Q4. What happens if the condition in a while loop is always false from the beginning?

Q5. How can you use break to exit a while loop early?

Q6. How do you use continue to skip a particular iteration in a while loop?

Q7. Write a while loop that prints only even numbers between 1 and 10.

Q8. How do you count backward using a while loop?

Q9. Can a while loop run even once if the condition is false at the beginning? Explain.

Q10. Write a while loop that stops when a variable reaches a randomly generated number.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top