loader

Loading

CoderrShyam logo

CoderrShyam

HomeAboutContactBlogTutorials
LoginSignup

Introduction

Quick StartWhat is JavaScriptHistory of JavaScript

Setup

Node.js InstallationVisual Studio Code

Basics

Syntax & Comments
Variables
For LoopsWhile Loop
Functions

Advanced

CoderrShyam logo

CoderrShyam

HomeAboutContactBlogTutorials
LoginSignup
TutorialsJavaScript TutorialLoopsWhile Loop

While Loop

The "while" loop in JavaScript is used to execute a block of code as long as a condition is true.

The while loop is a control structure in JavaScript that allows you to execute a block of code as long as a condition is true. It is called a while loop because it continues to execute the code block while the condition is true.

Syntax

Here is the syntax for a while loop in JavaScript:

main.js
while (condition) {
  // code to be executed
}

The condition is a boolean expression that evaluates to either true or false. The code inside the loop is executed as long as the condition is true. If the condition is false, the loop terminates, and the code after the loop is executed.

Examples

Here are some examples of using a while loop in JavaScript:

main.js
let count = 0;

while (count < 5) {
  console.log(count);
  count++;
}

In this example, the loop will execute 5 times, and the output will be:

0
1
2
3
4

Here is another example:

main.js
let x = 10;

while (x > 0) {
  console.log(x);
  x -= 2;
}

In this example, the loop will execute 5 times, and the output will be:

10
8
6
4
2

Infinite Loops

It is important to ensure that the condition in a while loop eventually becomes false; otherwise, the loop will continue to execute indefinitely. This is known as an infinite loop and can cause your program to become unresponsive or crash.

Here is an example of an infinite loop:

main.js
while (true) {
  console.log("This is an infinite loop!");
}

In this example, the condition true is always true, so the loop will continue to execute indefinitely.

Conclusion

  • The while loop is used to execute a block of code as long as a condition is true.
  • It is important to ensure that the condition in a while loop eventually becomes false to avoid infinite loops.
  • The while loop is useful when you do not know in advance how many times the loop will need to execute

How is this guide?

February 26th, 2026

For Loops

For loops are a common control flow structure in programming that allows you to repeat a block of code a specific number of times.

Functions

Functions are reusable blocks of code that perform a specific task. They allow you to break down your code into smaller, more manageable pieces.

© 2026CoderrShyamAll Rights Reserved.

On this page

Syntax
Examples
Infinite Loops
Conclusion
Follow us on GitHub