JavaScript
    About Lesson

    The for...of loop in JavaScript is used to iterate over iterable objects like arrays, strings, maps, sets, and more. It provides a concise and readable way to access the values of an iterable object directly.

     


    Syntax of for...of

     

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

     

    • variable: A variable that stores the current value of the iteration.
    • iterable: An object that is iterable (e.g., Array, String, Map, Set).

     


    Features of for...of

    1. Iterates Over Values
      The for...of loop retrieves the values of the iterable instead of the keys or indices.

    2. Works with Iterables
      It works seamlessly with iterable objects like arrays, strings, maps, sets, and more.

    3. Readable Syntax
      for...of is simpler and more readable than traditional loops for iterating over values.

     


    Examples

    1. Iterating Over an Array

     

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

    for (const fruit of fruits) {
    console.log(fruit);
    }
    // Outputs:
    // apple
    // banana
    // cherry

     

    2. Iterating Over a String

     

    const word = "hello";

    for (const letter of word) {
    console.log(letter);
    }
    // Outputs:
    // h
    // e
    // l
    // l
    // o

     

    3. Iterating Over a Set

     

    const uniqueNumbers = new Set([1, 2, 3, 4]);

    for (const num of uniqueNumbers) {
    console.log(num);
    }
    // Outputs:
    // 1
    // 2
    // 3
    // 4

     

    4. Iterating Over a Map

     

    const userRoles = new Map([
    ["Junaid", "Admin"],
    ["Arsheen", "Editor"],
    ["Kinza", "Viewer"]
    ]);

    for (const [user, role] of userRoles) {
    console.log(`${user}: ${role}`);
    }
    // Outputs:
    // Junaid: Admin
    // Arsheen: Editor
    // Kinza: Viewer



    Comparison: for...of vs for...in

    Featurefor...offor...in
    Iterates OverValues of the iterableKeys or indices
    Works OnArrays, Strings, Maps, Sets, etc.Objects, Arrays
    Use CaseAccessing valuesAccessing keys or properties

     


    Best Practices

    1. Use for Arrays and Strings
      When working with arrays or strings, for...of is simple and efficient.

    2. Avoid for Objects
      For plain objects, use for...in or Object.keys()/Object.values().

    3. Use with Maps and Sets
      for...of is ideal for iterating over key-value pairs in maps and unique elements in sets.

     


    The for...of loop is a modern and intuitive way to iterate over iterable objects in JavaScript. It simplifies accessing values and enhances code readability. While it’s not suitable for every scenario, it’s a powerful tool when working with arrays, strings, and other iterable structures.