JavaScript for

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

A classic for loop has three parts: start a counter, check a condition before each pass, then update the counter. Use it when you know how many times to repeat.

JavaScript Syntax

JavaScript
for (let i = 0; i < 3; i++) {
  console.log(i);
}
Try it Editor

How It Works

  1. i starts at 0.
  2. While i < 3. Body runs, then i++.
  3. Stops at 3. Condition becomes false.

Examples

Example 1 — Loop an array by index

Read each element with colors[i].

JavaScript
const colors = ["red", "green"];
for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}
Try it Editor

How It Works

  1. length is 2.
  2. Indexes 0 and 1 print.

Example 2 — Sum numbers

Accumulate in a variable.

JavaScript
let sum = 0;
for (let i = 1; i <= 4; i++) sum += i;
console.log(sum);
Try it Editor

How It Works

  1. Adds 1+2+3+4.
  2. Result is 10.

Example 3 — Stop early with break

Exit the loop immediately.

JavaScript
for (let i = 0; i < 10; i++) {
  if (i === 2) break;
  console.log(i);
}
Try it Editor

How It Works

  1. When i is 2, break ends the loop.
  2. 2 is never printed.

Frequently Asked Questions

When you need an index or a fixed count. Prefer for...of to walk values without indexes.
Use let. const cannot be reassigned by i++.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful