By the end of this lesson, you will understand how to use for and while loops to repeat tasks in JavaScript. Grasping these concepts is essential for efficient coding.
Loops are a fundamental part of programming. They allow you to execute a block of code multiple times. For instance, if you want to greet ten people, you could write the greeting code ten times. However, that would be tedious. Instead, you can use a loop to achieve this easily. These constructs save time and reduce errors in your code.
Both loop types have the same purpose: repeating tasks. However, their structures differ. A for loop is often used when you know the exact number of repetitions. On the other hand, a while loop is handy when repetitions depend on a specific condition.
File: greet.js
for (let i = 1; i <= 10; i++) {
console.log('Hello!');
}
Expected Output:
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Here’s a breakdown of the for loop code:
for (let i = 1; i <= 10; i++): This sets up the loop to start at 1 and repeat until it reaches 10.console.log('Hello!');: This line prints “Hello!” to the console.File: count.js
let count = 1;
while (count <= 10) {
console.log(count);
count++;
}
Expected Output:
1
2
3
4
5
6
7
8
9
10
This while loop works as follows:
let count = 1;: Initializes the counter variable.while (count <= 10): Checks if the counter is 10 or less.count++;: Increases the counter by 1 each time the loop runs, ensuring continuous counting.Now, create a simple countdown from 10 to 1 using a while loop. Print each number to the console. This task will help reinforce your understanding of looping constructs.
let countdown = 10;
while (countdown >= 1) {
console.log(countdown);
countdown--;
}
To learn more about JavaScript fundamentals, check out our What Is JavaScript? Examples from Everyday Websites lesson.