For Loop, Use & Syntax
jpabloc17
Posted on July 22, 2023
Sometimes we find that we have to write the same code many times. For example, having to print the numbers from 1 to 100 on the console would be very tedious nor would it be very efficient.
Here is when loops become handy:
Loops allow us to execute the same code a certain number of times. We can use a "for" loop instead of writing a console.log() 100 times.
For loop syntax:
The syntax consists of the keyword "for" followed by parentheses and curly braces (for(){})
Inside the braces we have the loop-body which is the code to be executed. Inside the parentheses we have the number of times our code is going to be executed. This is made up of several parameters separated by semicolons ";".
Initialization: This will be our starting point, here we can define a variable that will be used as our counter. Conts should not be used since its value will be changing, typically the initial value is 0 or 1.
Condition: Here we write the ending point. We must define how many times we want our code to be executed. This means that our loop will be executed while the condition is true.
It is important to have an ending point if we do not want our loop run an infinite number of times.
Iteration: The iteration is what is executed at the end of each loop. Here we will define what we want to happen with our variable. For example, increase or decrease its value.
Loop Body: This will be the code to execute for each time while the condition is true.
In this example we define our variable "i" equal to 1 since we want to print the numbers from 1 to 100. This would be our counter.
The condition would be that as long as the value of our variable "i" is less than or equal to 100, our loop will continue to execute.
For the iteration, each time our code is executed, one will be added to "i". In JS, we can do this using '++'.
For the body, we are using "i" inside the parentheses to print its value after each cycle.
As we can see using the "for" loop, we can get the same result without having to write 100 separate "console.log()". Loops are powerful tools that help us simplify and improve our code.
Posted on July 22, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
June 20, 2024