Javascript Loops

Javascript loop diagram.

Loops

Loops are a fundamental concept in programming that allow you to repeat a set of instructions multiple times without writing the same code repeatedly. Think of them as tools for automating tasks where you need to do something over and over, like counting numbers, processing a list of items, or running a set of calculations. By using loops, you can save time, reduce errors, and make your code more efficient and manageable. They’re like a cycle—you define the starting point, the condition to continue, and the action to repeat, and the loop takes care of the rest!
We will look at differnet javascript loops in this article.

Below is an example of a loop in Javascript.

for (let i = 0; i < 3; i++) {
    console.log("Hello World!");
}

Output:

Hello World
Hello World
Hello World

Type of Javascript Loops

1. For Loop

A for loop in JavaScript is used to repeat a block of code a specific number of times. It has three parts: a starting point, a condition to continue, and a step to update after each iteration. It’s perfect for tasks like looping through arrays or counting numbers.

Syntax:

for (let i = 1; i <= 5; i++) {
  console.log("Hello");
}

Output:

This loop starts at i = 1, runs as long as i <= 5, and increases i by 1 after each iteration. It will print:

Hello
Hello
Hello
Hello
Hello

2. While Loop

A while loop in JavaScript keeps running as long as the condition you provide is true. Unlike a for loop, it doesn’t have a built-in counter—you control the starting point, the condition, and when to stop. It’s useful when you don’t know in advance how many times the loop should run. Just be careful to update your condition within the loop; otherwise, it could run forever!

Syntax:

let count = 1;
while (count <= 5) {
  console.log("Hello");
  count++;
}

Output:

This loop starts with count = 1 and keeps running as long as count <= 5. After each iteration, count is increased by 1. The output will be:

Hello
Hello
Hello
Hello
Hello

3. Do-While Loop

A do...while loop in JavaScript is similar to a while loop but with one key difference: it always runs the code block at least once, even if the condition is false from the start. The reason is that the condition is checked after the code is executed. This makes it perfect for situations where you want the code to run first and then decide whether to repeat based on a condition. It ensures the loop executes at least once, no matter what!

Syntax:

let number = 1;
do {
  console.log("Hello");
  number++;
} while (number <= 5);

Output:

In this case, the loop runs the code block to print the number and then checks if number <= 5. It continues until the condition is false. The output will be:

Hello
Hello
Hello
Hello
Hello

4. ForEach Loop

The forEach loop in JavaScript is a simple way to iterate through the elements of an array. It runs a callback function for each item, giving you access to the current element, its index, and the entire array. Unlike for or while loops, forEach is specifically designed for arrays and is easier to read and write when working with them. However, it doesn’t support breaking out of the loop early.

Syntax:

let fruits = ['Apple', 'Banana', 'Orange'];

fruits.forEach(function(fruit, index) {
  console.log(`${index}, ${fruit}`);
});

Output:

In this example, the forEach loop iterates over each element in the fruits array, printing the index and the fruit name.

1, Apple
2, Banana
3, Orange

5. For-in Loop

The for...in loop in JavaScript is used to iterate over the properties of an object. It allows you to access each key in the object and perform actions with its corresponding value. This loop is useful when you need to work with the keys of an object, such as when you want to inspect or modify the properties.

Syntax:

let person = { name: 'John', age: 25, city: 'New York' };

for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}

Output:

In this example, the for...in loop goes through each property (key) of the person object and logs both the key and its value.

name: John
age: 25
city: New York

6. For-of Loop

The for...of loop in JavaScript is used to iterate over the values of iterable objects like arrays, strings, or even maps and sets. Unlike the for...in loop, which loops through object keys, for...of directly accesses the values, making it ideal for working with arrays or other iterable data types. It’s simple and easy to read, especially when you only need the values, not the indexes.

Syntax:

let colors = ['Red', 'Green', 'Blue'];

for (let color of colors) {
  console.log(color);
}

Output:

In this example, the for...of loop iterates over each value in the colors array and logs it directly.

Red
Green
Blue

Conclusion for Javascript Loops

Choosing the right javascript loops depends on your specific task. If you know the number of iterations in advance, a for loop might be your best choice. If you’re working with arrays and want a clean, easy-to-read solution, forEach or for...of could be more suitable. For tasks where the condition might change after each iteration, consider a while or do...while loop. Always think about the data structure you’re working with and the specific behavior you need, and choose the loop that makes your code simpler and more efficient.

Check out more of out posts:

Intersection Observer API

Portfolio Website

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *