Advertisement

Google Ad Slot: content-top

JS Loop for


A for loop is used to run a block of code repeatedly for a specified number of times, based on a condition. It is one of the most common control structures in JavaScript.


Syntax:

for (initialization; condition; increment/decrement) { 
  // Code to execute 
}


  • Initialization: Sets the starting value for the loop variable.
  • Condition: Specifies when the loop should stop (must evaluate to false to terminate the loop).
  • Increment/Decrement: Updates the loop variable after each iteration.
Basic Loop
for (let i = 0; i < 5; i++) {
console.log("Iteration number:", i);
}
Try it yourself

Iterating Over an Array
let fruits = ["Apple", "Banana", "Cherry"];

for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Try it yourself

Looping in Reverse
for (let i = 5; i > 0; i--) {
console.log("Iteration number:", i);
}
Try it yourself

Nested for Loop
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 2; j++) {
console.log(`Outer loop: ${i}, Inner loop: ${j}`);
}
}
Try it yourself