What is Loops?
Loops are a fundamental concept in programming that allows you to execute a set of instructions repeatedly for a specified number of times. They are used to simplify the code and make it more efficient.
There are three types of loops in JavaScript:
1. For loop
2. while loop
3. do-while loop
1. For Loop
The for loop is a control structure in JavaScript that allows you to execute a block of code a specific number of times. It is commonly used for iterating over arrays, performing calculations, or running repetitive tasks. It consists of three parts: initialization, condition, and increment.
Syntax
for (initialization; condition; increment/decrement) {
// Code to execute on each iteration
}
Explanation:
Initialization: This is where you define and initialize a variable (e.g., let i = 0). It runs once at the start of the loop.
Condition: This is the condition that must be true for the loop to continue. If it evaluates to false, the loop stops.
Increment/Decrement: This updates the loop control variable (e.g., i++ or i--) after each iteration.
Example
for (let i = 1; i <= 5; i++) {
console.log("Count: " + i);
}
a. Using a Decrementing Loop
You can count backward by decrementing the loop variable:
Explanation:
Start from 5 and decrement i using i-- until it reaches 1.
Example
for (let i = 5; i > 0; i--) {
console.log("Countdown: " + i);
}
b. Skipping Iterations(continue)
The continue statement skips the rest of the code for the current iteration and moves to the next one:
Explanation:
If the condition is met, the code inside the loop is skipped, and the loop continues with the next iteration.
Example
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip iteration when i equals 3
}
console.log("Number: " + i);
}
c. Breaking the Loop(break)
The break statement stops the loop completely:
Explanation:
If the condition is met, the loop stops, and the code after the loop is executed.
Example
for (let i = 1; i <= 5; i++) {
if (i === 4) {
break; // Exit the loop when i equals 4
}
console.log("Number: " + i);
}
Conclusion:
Use for loops for repetitive tasks or iterating over data.
The structure of a for loop is:for (initialization; condition; increment/decrement)
Use continue to skip an iteration.
Use break to exit the loop early.
Be careful to avoid infinite loops.