Loops - What is Loop & Types
Loops are used to:
- Execute a block of code repeatedly
- Run code until a specific condition is met
Definition:
A loop allows you to automate repetitive tasks instead of writing the same code multiple times.
Why Do We Need Loops?
Without loops:
console.log(1);
console.log(2);
console.log(3);
// ...
console.log(10);
Problems:
- Time-consuming
- Repetitive code
- Higher chances of mistakes
- Not scalable (imagine printing up to 1000)
With Loops:
for (let i = 1; i <= 10; i++) {
console.log(i);
}
Benefits:
- Less code
- Faster execution
- Easy to manage and scale
Real-Life Example
Printing Table of 10
Without loop:
10 * 1
10 * 2
...
10 * 10
With loop:
for (let i = 1; i <= 10; i++) {
console.log(10 * i);
}
Types of Loops in JavaScript
for Loop
- Most commonly used loop
- Used when number of iterations is known
while Loop
- Runs while condition is true
- Used when iterations are not fixed
do...while Loop
- Runs at least once (even if condition is false)
for...of Loop
- Used for arrays and iterable data
- Gives values directly
for...in Loop
- Used for objects
- Iterates over keys
Key Concept
- Loops execute code automatically multiple times
- You only write code once
- Loop controls repetition using conditions