Loops are statements that repeat an action for a specified number of times. they enable you to execute a block of code repeatedly until a certain condition is met.
The for
Loop
Syntax:
for (initialization; condition; increment/decrement ) {
//code to be executed
}
for loop consists of initialization, conditions, and increment/decrement.
the Initialization: is assigned to a variable e.g. ( i = 0 ).
the condition is decisions for the loop to run e.g. (i must be less than 5).
while increment/decrement increases (i++) or decreases (i--) each time the code block in the loop is executed.
for
loops are commonly used to run code a set number of times. Also, you can use break
to exit the loop early, before the condition
expression evaluates to false
.
Example
Interate through integers from 0-4
for ( i = 0; i < 5; i++ ) {
console.log("print: " + i);
}
//Output
//print: 0
//print: 1
//print: 2
//print: 3
//print: 4
Use break
to exit out of a for
loop before condition
is false
:
for ( i = 0; i < 5; i++ ) {
if(i == 2) {
break;
}
console.log("print: " + i);
}
//Output
//print: 0
//print: 1
//print: 2
The while
Loop
Syntax:
while (condition) {
//code to be executed
}
This loop through a block of code as long as the condition is true.
example;
let i = 0;
while ( i < 5 ) {
console.log("The number is " + i);
i++
}
//Output
//The number is 0
//The number is 1
//The number is 2
//The number is 3
//The number is 4
do while
Loop
Syntax:
do {
//code to be executed
}
while (condition);
This executes the block of code once before checking if the condition is true, then it will repeat the loop as long as the condition is true.
example;
do {
console.log("The number is " + i);
i++
}
while (i < 5);
//Output
//The number is 0
//The number is 1
//The number is 2
//The number is 3
//The number is 4
Conclusion
in conclusion, loops in programming especially JavaScript, are essential for executing a set of instructions repeatedly. They provide ways to automate tasks, iterating over data structure, objects, and arrays.
Thank you for reading.
References.