0
0
Javascriptprogramming~5 mins

For loop in Javascript

Choose your learning style9 modes available
Introduction

A for loop helps you repeat a task many times without writing the same code again and again.

When you want to count from 1 to 10 and do something each time.
When you have a list of names and want to greet each person.
When you want to add up numbers in a list.
When you want to repeat an action a fixed number of times.
When you want to process items in an array one by one.
Syntax
Javascript
for (initialization; condition; update) {
  // code to run each time
}

initialization sets a starting point, like let i = 0.

condition is checked before each loop; if true, the loop runs.

update changes the loop variable, usually increasing it.

Examples
This counts from 0 to 4 and prints each number.
Javascript
for (let i = 0; i < 5; i++) {
  console.log(i);
}
This counts down from 10 to 1 and prints each number.
Javascript
for (let count = 10; count > 0; count--) {
  console.log(count);
}
This goes through a list of fruits and prints each one.
Javascript
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
Sample Program

This program prints numbers from 1 to 5 with a message each time.

Javascript
for (let i = 1; i <= 5; i++) {
  console.log(`Number is ${i}`);
}
OutputSuccess
Important Notes

Remember the loop stops when the condition becomes false.

You can use break to stop the loop early if needed.

Using let inside the loop keeps the variable local to the loop.

Summary

A for loop repeats code a set number of times.

It has three parts: start, condition, and change.

Use it to work with lists or repeat tasks easily.