Learning For Loop In Javascript
Danities Ichaba
Posted on May 16, 2023
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)
}
In this example the output would be
0
1
2
3
4
5
let break it down
The initialization is let counter = 0, so the loop will start counting at 0.
The stopping condition is counter < 4, meaning the loop will run as long as the iterator variable, counter, is less than 4.
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.
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.
Posted on May 16, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.