Skip to content
The Chat Archive
gpt-4.1-2025-04-14· OpenAI LMArena Human Preference 140K

please give me examples of javascript loop: "for..of"

  1. User

    please give me examples of javascript loop: "for..of"

  2. Assistant

    Certainly! The for...of loop in JavaScript is used to iterate over iterable objects like arrays, strings, maps, sets, etc. Here are some examples:


    1. Looping through an Array

    const fruits = ['apple', 'banana', 'cherry'];
    
    for (const fruit of fruits) {
      console.log(fruit);
    }
    // Output:
    // apple
    // banana
    // cherry
    

    2. Looping through a String

    const word = "hello";
    
    for (const letter of word) {
      console.log(letter);
    }
    // Output:
    // h
    // e
    // l
    // l
    // o
    

    3. Looping through a Set

    const numbers = new Set([1, 2, 3]);
    
    for (const num of numbers) {
      console.log(num);
    }
    // Output:
    // 1
    // 2
    // 3
    

    4. Looping through a Map

    const map = new Map([
      ['a', 1],
      ['b', 2],
      ['c', 3]
    ]);
    
    for (const [key, value] of map) {
      console.log(key, value);
    }
    // Output:
    // a 1
    // b 2
    // c 3
    

    5. Looping through an Array of Objects

    const users = [
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 }
    ];
    
    for (const user of users) {
      console.log(user.name, user.age);
    }
    // Output:
    // Alice 25
    // Bob 30
    

    Let me know if you need more examples or explanations!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.