KandZ – Tuts

We like to help…!

JavaScript 13 🧬 loops part 1

a - loops introduction
Loops are used to execute a block of code repeatedly under certain conditions.
They allow you to perform tasks multiple times without writing the same code over and over again manually.
Here are some common uses and benefits:
1. Iterating Over Collections
2. Repeating Actions
3. Controlling Program Flow
JavaScript provides several types of loops to execute a block of code repeatedly under certain conditions.
those are: for, while, do...while, for...in and for...of loops

b - for loop
for loop is used when you know exactly how many times you want to run the loop.
syntax

for (initialization; condition; final-expression) {
// code block to be executed
}

It has three optional expressions: initialization, condition, and final expression.
Initialization: is executed only once before the loop starts, typically used to declare and initialize a loop counter variable.
Condition: is evaluated at the beginning of each iteration of the loop. If true, the code block inside the loop will be executed. If false, the loop will terminate.
Final-expression: is executed after each iteration of the loop, Ioften used to increment or decrement the loop counter variable.
example 1: will print numbers from 0 to 4
example 2: will print each fruit in the array
example 3: nested loop, will print the coordinates of a 3x3 grid
break statement can be used to terminate a loop prematurely when a specific condition is met.
continue statement is used within loops (like for, while, or do...while) to skip the current iteration of the loop

c - while and do...while loop
while loop allows you to repeatedly execute a block of code as long as a specified condition evaluates to true.
syntax:

while (condition) {
// Code block to be executed while the condition is true
}

example 1: will print numbers from 0 to 4
example 2: simple countdown timer
do...while loop is similar to while loop but with one key difference
it guarantees that the code block will execute at least once before checking the condition.
syntax:

do {
// Code block to be executed
} while (condition);

example: ensures user input at least once

Leave a Reply