Sat Mar 11 2023

Understanding the Various Types of for Loops

JavaScript115 views

Loops are an essential part of writing efficient, dynamic, and scalable code in any programming language. They allow you to repeat a block of code multiple times, iterating through arrays, objects, or performing repetitive tasks. JavaScript also offers several types of loops, each suited to different tasks. In this article, we'll focus on the different types of for loops in JavaScript, including the traditional for loop, for...in and for...of.

1. The Traditional for Loop

The traditional for loop is one of the most basic looping structures in JavaScript. It is versatile and can be used to iterate over arrays or run repetitive code based on certain conditions.

Syntax:

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

  • Initialization: Sets a variable that will be checked and updated (usually an index).

  • Condition: Specifies a condition that determines whether the loop will continue.

  • Increment/Decrement: Updates the loop control variable after each iteration.

const num = [25, 45, 81, 64, 10, 46, 89, 49];

for(let i = 0; i < num.length; i++) {
document.getElementById('loop1').innerHTML += num[i] + '<br />';
}

2. for...in Loop

The for...in loop is used to iterate over the properties (keys) of an object. It is particularly useful for objects but can also be used with arrays (though not recommended).

Syntax:

for (key in object) {
// Code to execute
}
const product = {
title: 'Web template',
price: 'Free',
website: 'webgraphiz.com'
};

for(let j in product) {
document.getElementById('loop2').innerHTML += j + ":" + product[j] + '<br />';
}

3. for...of Loop

The for...of loop was introduced in ES6 (ES2015) and is designed specifically for iterating over iterable objects like arrays, strings, maps, sets, and more. Unlike for...in, it returns the values of the iterable, making it more suitable for arrays.

Syntax:

for (value of iterable) {
// Code to execute
}

const site = "webgraphiz.com"

for(let k of site) {
document.getElementById('loop3').innerHTML += k + '<br />';
}

Differences Between the Loops

  • for loop: A general-purpose loop, useful for iterating over arrays when you need to access both the index and the value.

  • for...in loop: Best suited for iterating over object properties but not recommended for arrays (as it iterates over indices).

  • for...of loop: Ideal for iterating over iterable objects like arrays, strings, maps, sets, and more.

Conclusion

JavaScript offers multiple ways to handle loops, each with its advantages and specific use cases. The traditional for loop is great for general-purpose iteration, while for...in is mainly used for objects. The for...of loop is perfect for arrays. By understanding the various types of for loops in JavaScript, you can choose the right one depending on your specific needs, leading to cleaner, more efficient code.

Understanding the Various Types of for Loops

File Name: javascript-for-loops.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Various Kind of For Loops</title>
    <style>
        section {
            display: flex;
            gap: 10;
            justify-content: space-between;
        }

        section div.col {
            width: calc(100% / 3);
        }

        button { margin-bottom: 10px; }
    </style>
    
    <script>
        const num = [25, 45, 81, 64, 10, 46, 89, 49];
        const product = {
            title: 'Web template',
            price: 'Free',
            website: 'webgraphiz.com'
        };
        const site = "webgraphiz.com"

        /* For Loop */
        const fstLoop = () => {
            for(let i = 0; i < num.length; i++) {
                document.getElementById('loop1').innerHTML += num[i] + '<br />';
            }
        }

        /* For In Loop */
        const sndLoop = () => {
            for(let j in product) {
                document.getElementById('loop2').innerHTML += j + ":" + product[j] + '<br />';
            }
        }

        /* For Of Loop */
        const trdLoop = () => {
            for(let k of site) {
                document.getElementById('loop3').innerHTML += k + '<br />';
            }               
        }
    </script>
</head>
<body>
    <section>
        <div class="col">
            <h3>For Loop</h3>
            <button type="button" onclick="fstLoop()">Loop1</button>
            <div id="loop1"></div>
        </div>
        <div class="col">
            <h3>For In Loop</h3>
            <button type="button" onclick="sndLoop()">Loop2</button>
            <div id="loop2"></div>
        </div>
        <div class="col">
            <h3>For Of Loop</h3>
            <button type="button" onclick="trdLoop()">Loop3</button>
            <div id="loop3"></div>
        </div>
    </section>
</body>
</html>

Result Screenshot(s)

Understanding the Various Types of for LoopsWorking Sample0

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.