DEV Community

Adhi sankar
Adhi sankar

Posted on

looping concept

Introduction

When writing programs, we often need to perform the same task multiple times. Instead of writing the same code repeatedly, JavaScript provides loops to automate repetition. Looping makes code shorter, cleaner, and more efficient.

What is a Loop?

A loop is a programming structure that repeatedly executes a block of code until a condition becomes false.

JavaScript provides several types of loops:

while loop

do...while loop

for loop

1. While Loop

The while loop runs as long as the condition is true.

JavaScript

Syntax

while(condition){
// code
}

Example:

Output:

2. Do...While Loop

This loop executes the code at least once, even if the condition is false.

JavaScript

Syntax

do {
// code
} while(condition);

Example:

3. For Loop

The for loop is the most commonly used loop.

JavaScript

Syntax

for(initialization; condition; increment) {
// code
}

Practical Example: Print Prime Numbers from 1 to 100
Benefits of Looping

Reduces code repetition.

Makes programs shorter and cleaner.

Improves readability.

Saves development time.

Handles large amounts of data efficiently.

Common Mistake: Infinite Loop

If the loop condition never becomes false, the program keeps running forever.

Example:

Always ensure that the loop variable changes properly.

Conclusion

Looping is one of the most important concepts in JavaScript. Whether you are printing numbers, processing arrays, checking prime numbers, or building real-world applications, loops help you perform repetitive tasks efficiently. Mastering while, for, and other loops is a strong step toward becoming a better JavaScript developer.

Top comments (0)