DEV Community

Danities Ichaba
Danities Ichaba

Posted on

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)