JavaScript

Understanding the Various Types of for Loops

Different types of for loops in JavaScript, including the traditional for loop, for...in and for...of

3/11/2023
0 views
javascript-for-loops.htmlHTML
<!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>
JavascriptFor LoopFor In loopFor Of loop

Loading comments...

Related Examples

6-Digit OTP Verification System for Web Security
JavaScript

6-Digit OTP Verification System for Web Security

Create a Digital Clock from Scratch
JavaScript

Create a Digital Clock from Scratch

Creative and Stunning Image Gallery
JavaScript

Creative and Stunning Image Gallery

Drag & Drop Functionality for Images
JavaScript

Drag & Drop Functionality for Images

Array Iteration in JavaScript: Using reduce, reduceRight, every, and some
JavaScript

Array Iteration in JavaScript: Using reduce, reduceRight, every, and some

Array Iteration in JavaScript: A Comprehensive Guide Part 1
JavaScript

Array Iteration in JavaScript: A Comprehensive Guide Part 1