JavaScript Loop For Of

The for...of loop iterates over iterable objects (such as arrays, strings, or maps), providing a simpler way to access each element directly, without using indices.

Key Topics

for...of with Arrays

Using for...of on an array returns each element in sequence.

let arr = ["A", "B", "C"];
for (let element of arr) {
    console.log(element);
}

Output

> A

> B

> C

Explanation: Each loop iteration assigns the next array element to element, making iteration more readable.

for...of with Strings

for...of can also iterate over characters in a string.

let word = "Hello";
for (let char of word) {
    console.log(char);
}

Output

> H

> e

> l

> l

> o

Explanation: The loop goes through each character in the string "Hello".

JavaScript Usage in DOM

Use for...of to simplify displaying lists of items or processing characters in a user input string on the webpage.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>For Of in DOM</title>
</head>
<body>
    <h1>For Of Demo</h1>
    <button onclick="showElements()">Show Elements</button>
    <div id="output"></div>

    <script>
        function showElements() {
            let items = ["Item1", "Item2", "Item3"];
            let result = "";
            for (let item of items) {
                result += item + " ";
            }
            document.getElementById("output").textContent = result;
        }
    </script>
</body>
</html>

Key Takeaways

  • for...of: Iterates over iterable objects like arrays or strings.
  • Simplicity: Access elements directly without indices.
  • DOM Integration: Easily display lists or characters on the webpage.