DEV Community

Danities Ichaba
Danities Ichaba

Posted on

1 1

Learning For Loop In Javascript

Instead of writing out the same code over and over, loops allow us to tell computers to repeat a given block of code on its own. One way to give computers these instructions is with a for loop.

A for loop declares looping instructions, with three important pieces of information separated by semicolons ;:

The initialization defines where to begin the loop by declaring (or referencing) the iterator variable.
The stopping condition determines when to stop looping (when the expression evaluates to false)
The iteration statement updates the iterator each time the loop is completed.

The for loops syntax look like this

for(let counter = 0; counter < 5; counter++){
       console.log(counter)

}
Enter fullscreen mode Exit fullscreen mode

In this example the output would be

0
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

let break it down

  1. The initialization is let counter = 0, so the loop will start counting at 0.

  2. The stopping condition is counter < 4, meaning the loop will run as long as the iterator variable, counter, is less than 4.

  3. The iteration statement is counter++. This means after each loop, the value of counter will increase by 1. For the first iteration counter will equal 0, for the second iteration counter will equal 1, and so on.

  4. The code block is inside of the curly braces, console.log(counter), will execute until the condition evaluates to false. The condition will be false when counter is greater than or equal to 4 — the point that the condition becomes false is sometimes called the stop condition.

This for loop makes it possible to write 0, 1, 2, and 3 programmatically.

Now, make your own! Create a program that loops from 5 to 10 and logs each number to the console.

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay