Track: JavaScript Basics
Lesson: JS-04 / JS-10
๐ฏ Lesson Goal
By the end of this lesson, you will be able to repeat tasks efficiently using JavaScript loops and apply loops to solve real programming problems.
๐ Prerequisites
- JS-01: Variables and Data Types
- JS-02: Operators and Expressions
- JS-03: Conditional Statements
You should understand:
- Variables and conditions
- Comparison and logical operators
๐ Why Do We Need Loops?
In programming, many tasks repeat:
- Display numbers from 1 to 10
- Print student names from a list
- Calculate totals or averages
- Repeat actions until a condition is met
Loops help us avoid writing the same code again and again.
๐น The for Loop
The most commonly used loop when the number of iterations is known.
Syntax
for (initialization; condition; increment/decrement) {
// code to repeat
}
Example: Print numbers 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
โ Output:
1
2
3
4
5
๐น The while Loop
Used when the number of repetitions is not fixed in advance.
Syntax
while (condition) {
// code
}
Example
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
๐น The do...while Loop
Executes the loop at least once, even if the condition is false.
Syntax
do {
// code
} while (condition);
Example
let number = 6;
do {
console.log(number);
number++;
} while (number <= 5);
โ Output:
6
๐น Loop Control Statements
break
Stops the loop immediately.
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
โ Output:
1 2 3 4
continue
Skips the current iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
โ Output:
1 2 4 5
๐น Nested Loops
A loop inside another loop.
Example
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 2; j++) {
console.log(i, j);
}
}
๐น Looping Through Arrays
Loops are commonly used with arrays.
Example
let languages = ["HTML", "CSS", "JavaScript", "React"];
for (let i = 0; i < languages.length; i++) {
console.log(languages[i]);
}
โ ๏ธ Common Mistakes
- Infinite loops (forgetting increment/decrement)
- Wrong loop condition
- Off-by-one errors (
<=vs<) - Modifying loop variable incorrectly
๐ง Practice Tasks
- Print numbers from 10 to 1
- Print all even numbers between 1 and 20
- Calculate the sum of numbers from 1 to 100
- Loop through an array of names
- Stop a loop when value reaches 7
๐งช Mini Coding Challenge
let numbers = [10, 15, 20, 25, 30];
- Use a loop to calculate the total
- Print only numbers greater than 20
๐ Summary
- Loops repeat code efficiently
foris used when iterations are knownwhileanddo...whilehandle dynamic conditionsbreakandcontinuecontrol loop execution- Loops work naturally with arrays
โก๏ธ Next Lesson
JavaScript Functions (JS-05)
๐ Quiz & Badge
Quiz and badges will be enabled soon.