Q1. What is a loop in JavaScript?
A loop is used to execute a block of code repeatedly until a specific condition is met.
Loops help avoid writing the same code multiple times and make programs more efficient.
Example
Output
The loop runs five times and prints numbers from 1 to 5.
Loops help avoid writing the same code multiple times and make programs more efficient.
Example
for(let i = 1; i <= 5; i++) { console.log(i);}Output
12345The loop runs five times and prints numbers from 1 to 5.
Q2. What Are the Different Types of Loops in JavaScript?
JavaScript provides several types of loops:
1. for loop
Used when the number of iterations is known.
2. while loop
Used when the number of iterations depends on a condition.
3. do...while loop
Runs at least once before checking the condition.
4. for...in loop
Used to iterate over object properties.
5. for...of loop
Used to iterate over iterable objects like arrays or strings.
Used when the number of iterations is known.
2. while loop
Used when the number of iterations depends on a condition.
3. do...while loop
Runs at least once before checking the condition.
4. for...in loop
Used to iterate over object properties.
5. for...of loop
Used to iterate over iterable objects like arrays or strings.
Q3. What is a For Loop?
A for loop runs a block of code for a specific number of times.
Exmaple
Output
Explanation:
Exmaple
for(let i = 0; i < 3; i++) { console.log("Hello");}Output
HelloHelloHelloExplanation:
- Initialization runs once.
- Condition is checked before each iteration.
- Increment updates the counter.
Q4. What is a While Loop?
A while loop executes code as long as the condition remains true.
Example
Output
The loop runs until i becomes greater than 3.
Example
let i = 1;
while(i <= 3) { console.log(i); i++;}Output
123The loop runs until i becomes greater than 3.
Q5. What is the Break Statement in Loops?
The break statement stops the loop completely when a condition is met.
Example
Output
The loop stops when i becomes 3.
Example
for(let i = 1; i <= 5; i++) { if(i === 3) { break; } console.log(i);}Output
12The loop stops when i becomes 3.
