Javascript

Introduction to For Loops

Introduction to For Loops in JavaScript

When you want to repeat a block of code multiple times, instead of writing it again and again, you use loops. The most common loop is the for loop.


What is a For Loop?

A for loop runs a block of code a specific number of times — great for going through arrays, counting, or repeating tasks.


Basic Syntax of a For Loop

js
for (initialization; condition; update) {
// code to run on each loop
}
  • Initialization: Start point (usually a counter variable)

  • Condition: Runs the loop while this is true

  • Update: What happens after each loop iteration (e.g., increment counter)


Example: Counting from 1 to 5

js
for (let i = 1; i <= 5; i++) {
console.log(i);
}

Output:

1
2
3
4
5

Breaking Down the Example

  • let i = 1; — Start counting at 1

  • i <= 5; — Continue loop as long as i is less than or equal to 5

  • i++ — Increase i by 1 each time (same as i = i + 1)


Using For Loops with Arrays

You can loop through an array’s elements like this:

js
const fruits = ["apple", "banana", "cherry"];

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

Output:

nginx
apple
banana
cherry

Why Use For Loops?

  • Automate repetitive tasks

  • Process every item in a list or array

  • Write cleaner, shorter code


Summary

Part Meaning
Initialization Where to start (e.g., let i = 0)
Condition When to keep looping (i < 10)
Update How to change each loop (i++)

Leave a Reply

Your email address will not be published. Required fields are marked *