0
0
Javascriptprogramming~5 mins

Loop execution flow in Javascript

Choose your learning style9 modes available
Introduction

Loops help repeat actions many times without writing the same code again and again.

When you want to count numbers from 1 to 10.
When you need to check each item in a list one by one.
When you want to keep asking a question until the answer is correct.
When you want to repeat a task a fixed number of times.
When you want to process data step by step automatically.
Syntax
Javascript
for (initialization; condition; update) {
  // code to repeat
}

// or

while (condition) {
  // code to repeat
  // update step inside
}

Initialization runs once at the start.

Condition is checked before each loop; if false, loop stops.

Examples
This prints numbers 0, 1, 2 one by one.
Javascript
for (let i = 0; i < 3; i++) {
  console.log(i);
}
This does the same as the for loop but uses while.
Javascript
let count = 0;
while (count < 3) {
  console.log(count);
  count++;
}
Sample Program

This program repeats a greeting 5 times, showing the step number each time.

Javascript
for (let i = 1; i <= 5; i++) {
  console.log(`Step ${i}: Hello!`);
}
OutputSuccess
Important Notes

Loops check the condition before running the code inside each time.

If the condition is false at the start, the loop code never runs.

Be careful to update variables inside the loop to avoid endless loops.

Summary

Loops repeat code while a condition is true.

Use for loops when you know how many times to repeat.

Use while loops when you repeat until a condition changes.