JavaScript Loops
JavaScript Loops
Loops in JavaScript allow a block of code to run multiple times as long as a given
condition is satisfied. They help reduce repetition and make programs more
efficient and organized.
Loops continue running until the condition becomes false.
They are useful for iterating over arrays, strings, and ranges of values.
In JavaScript, there are three types of Loops :
1. for Loop
The for loop repeats a block of code a specific number of times. It contains
initialization, condition, and increment/decrement in one line.
Syntax
for (initialization; condition; increment/decrement) {
// Code to execute}
Example: The below JavaScript program for loop runs from i = 1 to i = 3,
incrementing i by 1 each time, and prints "Count:" followed by the current value of
i.
[Link](function(num) {
[Link](num);
});
2. while Loop
The while loop executes as long as the condition is true. It can be thought of as a
repeating if statement.
Syntax
while (condition) {
// Code to execute
}
Example: The below JavaScript program while loop prints "Number:" followed by
i repeatedly while i is less than 3, incrementing i by 1 each time.
let i = 0;
while (i < 3) {
[Link]("Number:", i);
i++;
}
The image below demonstrates the flow chart of a while loop:
While loop starts with the checking of Boolean condition. If it evaluated to true,
then the loop body statements are executed otherwise first statement following
the loop is executed. For this reason it is also called Entry control loop
Once the condition is evaluated to true, the statements in the loop body are
executed. Normally the statements contain an update value for the variable
being processed for the next iteration.
When the condition becomes false, the loop terminates which marks the end
of its life cycle.
3. do-while Loop
The do-while loop is similar to while loop except it executes the code block at
least once before checking the condition.
Syntax
do {
// Code to execute
} while (condition);
Example: The below JavaScript program do-while loop prints "Iteration:" followed
by i, increments i by 1, and repeats the process while i is less than 3, ensuring
the block runs at least once.
let i = 0;
do {
[Link]("Iteration:", i);
i++;
} while (i < 3);
The image below demonstrates the flow chart of a do-while loop:
do while loop starts with the execution of the statement. There is no checking
of any condition for the first time.
After the execution of the statements, and update of the variable value, the
condition is checked for true or false value. If it is evaluated to true, next
iteration of loop starts.
When the condition becomes false, the loop terminates which marks the end
of its life cycle.
It is important to note that the do-while loop will execute its statements a tleast
once before any condition is checked, and therefore is an example of exit
control loop.