Josh Writes

Small boy with big dreams.

JavaScript Loops are Easy!.. (actually)

Hello, welcome to today’s blog! My names Josh Garrett!
Hello, welcome to today’s blog! My names Josh Garrett!
Hello, welcome to today’s blog! My names Josh Garrett!

Oh, woops! Accidentally used a loop heh. 😉
Today we shall learn about loops in JavaScript! Let’s get started!

Introduction

You’re a startup developer, and you just received an assignment: create a report that prints out daily sales data for last week. Producing individual code for every day would be counterproductive, so how do you approach this in a better way? That is where loops step in!

Loops are a cornerstone of programming—enabling you to repeat code without having to type it out several times. Here in this blog, we’ll be taking a look at JavaScript’s for loops, while loops, and do-while loops. We’ll also take a look at the common mistakes that can produce bugs and how to prevent them.

What Are Loops?

Loops assist you in automating repetitive programming tasks. Rather than typing individual lines of code for every repetition, you utilize a loop to run the same code repeatedly under a given condition. The three main types of loops in JavaScript are:

  • For loop – Most suitable when the number of iterations is known in advance.
  • While loop – Most suitable when the number of iterations is unknown but based on a condition.
  • Do-while loop – Makes sure that the body of the loop gets executed at least once before checking for the condition.

Let’s examine some examples so that we get a better sense of them.

Learning about the For Loop

The for loop is mostly applied when you’re aware of the number of times you’ll execute a chunk of code. The following is an example:

// JavaScript for loop example
for (let i = 0; i < 5; i++) {  
    console.log(`Iteration number: ${i}`);  
}

Suppose you wish to loop through a shopping list contained in an array. Because you can calculate the array’s length using array.length, a for loop is an excellent option!

How It Works:

  • Initialization: Initializes the loop counter.
  • Condition: Specifies how many times the loop will execute.
  • Iteration: Increments the counter after every loop iteration.

Example:

let groceryList = ["tomato", "potato", "cabbage"];  
for (let i = 0; i < groceryList.length; i++) {  
    console.log(groceryList[i]);  
}

Common Mistakes to Avoid:

  • Off-by-One Errors: Ensure the loop condition accurately reflects the required number of iterations.
  • Infinite Loops: Always update the loop counter to prevent endless execution.

Understanding the While Loop

A while loop is useful when the number of iterations isn’t known in advance. It runs as long as the specified condition remains true.

// Example of a while loop in JavaScript
let count = 0;  
while (count < 5) {  
    console.log(`Count is: ${count}`);  
    count++; // Don't forget to increment your counter!  
}

How It Works:

  • The loop begins with count = 0.
  • The condition count < 5 controls the continuation of the loop.
  • Within the loop, count++ increments the variable to avoid infinite looping.

Key Takeaways:

  • While loops are handy when the number of iterations is not known in advance.
  • Always increment the condition variable within the loop to avoid infinite loops.

Understanding the Do-While Loop

The do-while loop is like the while loop but ensures the code is executed at least once before testing the condition.

// JavaScript example of a do-while loop
let num = 0;  
do {  
    console.log(`Number is: ${num}`);  
    num++;  
} while (num < 5);

How It Works:

  • The loop runs the block first before it checks num < 5.
  • If the condition remains true, the loop repeats.
  • If false, the loop ends.

This is handy when you want the code to run at least once, even if the condition is not met yet.

Preventing Common Bugs in Loops

Loops can lead to problems if not managed well. Here are some common bugs and how to avoid them:

1. Infinite Loops

  • Make sure your loop has a proper exit condition always.
  • Make sure your loop counter gets updated correctly within the loop.

Example of an infinite loop:

let i = 0;  
while (i < 5) {  
    console.log(i);  
    // Oops! Forgot to increment 'i', so this runs forever  
}

Fix: Add i++ within the loop.

2. Off-By-One Errors

  • Double-check your loop condition to prevent extra or missing iterations.
  • Keep in mind that JavaScript arrays are zero-indexed.

Example of an off-by-one error:

let arr = ["a", "b", "c"];  
for (let i = 0; i <= arr.length; i++) { // Incorrect condition (should be < arr.length)  
    console.log(arr[i]);  
}

3. Misplaced Code Within the Loop

  • Make sure only essential operations are within the loop.
  • Don’t put unnecessary reassignments within loops, as this will decrease performance.

Recap

We discussed:

  • For loops – Most suitable for a known number of iterations.
  • While loops – Ideal when the number of iterations is unknown in advance.
  • Do-while loops – Guarantees the loop will execute at least once.
  • Common bugs to avoid – Be careful of infinite loops, off-by-one errors, and misplaced code.

Practice Makes Perfect

Practice is the most effective way to become proficient at loops. Practice writing various loops in JavaScript and changing conditions and observe how they react.

Final Thoughts

Loops are a programmer’s friend, enabling you to write lean and clean code. By mastering their behavior and steering clear of common traps, you will become a better JavaScript programmer.

Have any questions or tips of your own? Add them to the comments below. Happy coding!