≡ Menu

🚀 Mastering JavaScript Loops: A Beginner’s Tutorial

Loops are a fundamental concept in programming, allowing you to execute a block of code repeatedly.

Instead of writing the same code over and over, loops help you automate repetitive tasks efficiently.

In JavaScript, there are several types of loops, each suited for different situations.

1. The for Loop: The Go-To Repeater

The for loop is the most common and generally the most structured loop.

It’s perfect when you know exactly how many times you want the loop to run (e.g., iterating through an array or counting to a specific number).

Structure

The for loop has three main expressions inside its parentheses, separated by semicolons:

  1. Initialization: Executed once before the loop starts. This usually initializes a counter variable (e.g., i=0).

  2. Condition: Evaluated before each loop iteration. If it’s true, the loop continues; if false, the loop stops.

  3. Increment/Decrement: Executed after each loop iteration. This usually updates the counter variable (e.g., i++).

Example

Let’s print the numbers from 1 to 5:

for (let i = 1; i <= 5; i++) {
  console.log("Count: " + i);
}
/*
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
*/

2. The while Loop: Condition-Based Running

The while loop runs as long as a specified condition remains true. It’s ideal when you don’t know the exact number of iterations beforehand, but you know the condition that must be met to stop the loop.

Structure

The while loop only requires a condition inside its parentheses. Crucially, you must manage the variable that controls the condition inside the loop’s body to prevent an infinite loop.

Example

Let’s do the same counting exercise with a while loop:

let count = 1;

while (count <= 5) {
  console.log("Count: " + count);
  count++; // Don't forget to update the counter!
}
/*
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
*/

3. The do...while Loop: Guaranteed Execution

The do...while loop is very similar to the while loop, but with one key difference: the code block is executed at least once before the condition is checked.

Structure

The do block executes, and then the while condition is checked.

Example

Even if the condition is initially false, the do block runs once:

let j = 10;

do {
  console.log("This will print once: " + j);
  j++;
} while (j < 5); // The condition is false (10 < 5 is false)
/*
Output:
This will print once: 10
*/

4. Loops for Iterating Collections (Arrays)

JavaScript provides specialized loops for easily working with arrays and other iterable objects.

A. for...of: Iterating Over Values

The for...of loop iterates over the values (elements) of an iterable object (like an array, string, or map).

const fruits = ["apple", "banana", "cherry"];

for (const fruit of fruits) {
  console.log("I like " + fruit);
}
/*
Output:
I like apple
I like banana
I like cherry
*/

B. for...in: Iterating Over Object Properties (Keys)

The for...in loop iterates over the enumerable properties (keys/indexes) of an object. While it can be used for arrays, it’s generally discouraged in favor of for, for...of, or Array.prototype.forEach().

const user = { name: "Alice", age: 30, city: "NY" };

for (const key in user) {
  console.log(key + ": " + user[key]);
}
/*
Output:
name: Alice
age: 30
city: NY
*/

🛑 Loop Control Statements

Sometimes you need to jump out of a loop or skip an iteration. That’s where control statements come in.

  • break: Immediately exits the entire loop. Execution continues with the code following the loop.

  • continue: Skips the rest of the current iteration and jumps to the next iteration of the loop.

Example:

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    continue; // Skip the number 3
  }
  if (i === 5) {
    break; // Stop completely when we hit 5
  }
  console.log(i);
}
/*
Output:
1
2
4
*/

Loops are the backbone of automated tasks in JavaScript.

Understanding when to use a for, while, or for...of loop is key to writing clean, efficient, and powerful code!

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments… add one }

Leave a Comment