β Blogs
Loops - Repeating Tasks in Code
In programming, you'll often need to do something multiple times β like print numbers, process lists, or check values.
Instead of writing the same code over and over, we use loops to automate repetition.
π What is a Loop?
A loop is a tool that allows your code to repeat a block of instructions until a condition is met.
β
Types of Loops in JavaScript
Letβs look at the most common ones:
π 1. for Loop
Use it when you know how many times you want to run the code.
for (let i = 1; i <= 5; i++) {
console.log("Number:", i);
} i= 1: Start at 1
i <= 5: Run as long as i β€ 5
i++: Increase i by 1 each time
π 2. while Loop
Use it when the condition is checked before each run.
let count = 1;
while (count <= 3) {
console.log("Count:", count);
count++;
}π 3. do...while Loop
Runs the block at least once, then checks the condition.
let num = 1;
do {
console.log("Num:", num);
num++;
} while (num <= 2);π¦ 4. for...of Loop (Used with arrays)
Great for looping throught items in an array.
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}π§ Quick Tip
π§ Donβt forget to update the loop condition β or your loop might run forever! (infinite loop ππ±)
π§ͺ Practice Challenge
Try this:
for (let i = 0; i < 4; i++) {
console.log("JS is fun!");
}Then change it to print numbers 1 to 10, or loop through an array of fruits.
π Sign-Off
Loops help you do more with less code. Theyβre the heart of automation in programming.
Next up, weβll dive into Arrays β and how to manage lists of values.
Want to work together?
Get answers and advice from people you want it from. Techsphere designers and developers will help you create awesome softwares based on your requirements.