DEV Community

Narmatha
Narmatha

Posted on

LOOP IN JAVASCRIPT

For Loop in JavaScript

A for loop in JavaScript is used to execute a block of code repeatedly as long as a given condition is true.

Instead of writing the same code many times, we can use a loop to repeat it automatically.

for (initialization; condition; increment/decrement) {
// code to be executed
}

for loop has three important parts:

1.Initialization – Runs only once at the beginning.
2.Condition – Checked before every iteration. If it is true, the loop runs.
3.Increment/Decrement – Changes the value after each iteration.

While loop in javascript

A while loop is used when you want to repeatedly execute a block of code as long as a condition is true.

Check condition → Execute code → Update something → Check again

1. Basic syntax

while (condition) {
// code to execute
}

for example

`let i = 1;

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

output

1
2
3
4
5

Top comments (0)