October 01, 2024

Loops in JavaScript: for, while, do...while

Introduction to Loops


  • Loops in JavaScript are like those repetitive tasks in life that you wish you could automate—like brushing your teeth every morning. They let you run a block of code multiple times, which is perfect when you need to perform the same action over and over again without writing the same lines of code repeatedly.


1. for Loop: The Workhorse


The for loop is the most commonly used loop in JavaScript. It’s like a to-do list—you know exactly how many tasks (iterations) you need to complete.


Syntax:


for (initialization; condition; increment) {
    // Code to be executed
}   


Example:


for (let i = 0; i < 5; i++) {
    console.log("This is loop iteration number " + (i + 1));
}  


In Action: The loop starts with i set to 0, checks the condition (i < 5), and runs the code inside the loop. After each iteration, i increases by 1. Once i reaches 5, the loop stops. It’s like counting reps at the gym—one, two, three, four, five, done!


2. while Loop: The Patient Observer


  • The while loop is like a game of “I Spy” where you keep looking until you find what you’re searching for. It continues to run as long as a specified condition remains true.


Syntax:


while (condition) {
    // Code to be executed
}  


Example:


let countdown = 5;

while (countdown > 0) {     console.log("Countdown: " + countdown);     countdown--; }


In Action: This loop keeps counting down from 5 until it reaches 0. If the condition starts out false, the code inside the loop will never run, kind of like realizing you’re out of coffee before even brewing a cup.


3. do...while Loop: The Optimist


The do...while loop is like that friend who insists on trying new food before they ask what’s in it. This loop will execute the block of code once, and then keep running as long as the condition is true.


Syntax:


do {
    // Code to be executed
} while (condition);  


Example:


let number = 0;

do {     console.log("Number is " + number);     number++; } while (number < 3);


In Action: Here, the code inside the do block runs at least once, even if the condition is false from the start. It’s like diving into the pool before checking if it’s cold—sometimes, you just have to go for it!


Conclusion:


Loops are a powerful tool in JavaScript, allowing you to automate repetitive tasks with minimal code. Whether you prefer the straightforwardness of a for loop, the flexibility of a while loop, or the adventurous spirit of a do...while loop, mastering these will make your coding life much easier. So, loop away and let JavaScript do the heavy lifting for you!


Loops
Loop Control Structures
Repetitive Tasks in Code
JavaScript Basics