Sobes.tech
Junior

What types of for loops do you know in JavaScript?

sobes.tech AI

Answer from AI

In JavaScript, there are several types of for loops:

  • for (classic): Used for iterating over a range of numbers or executing a block a certain number of times.

    // Iterating over a range of numbers
    for (let i = 0; i < 5; i++) {
      console.log(i); // 0, 1, 2, 3, 4
    }
    
  • for...in: Iterates over the keys (properties) of an object, including properties in its prototype chain. Not recommended for array iteration due to potential issues with order and non-numeric properties.

    const obj = { a: 1, b: 2, c: 3 };
    for (const key in obj) {
      console.log(`${key}: ${obj[key]}`);
      // a: 1
      // b: 2
      // c: 3
    }
    
    const arr = ['apple', 'banana', 'orange'];
    for (const index in arr) {
      console.log(index); // 0, 1, 2 (keys are indices in this case)
    }
    
  • for...of: Iterates over the values of iterable objects such as arrays, strings, Map, Set, TypedArray, and arguments. Recommended for array iteration.

    const arr = ['apple', 'banana', 'orange'];
    for (const element of arr) {
      console.log(element);
      // apple
      // banana
      // orange
    }
    
    const str = "hello";
    for (const char of str) {
      console.log(char);
      // h
      // e
      // l
      // l
      // o
    }
    

Comparison table:

Loop Purpose Iterated elements Recommended for
for Iterating over a numeric range, repeating A specific number of times General loops
for...in Iterating over keys (properties) of objects Keys (properties) Objects
for...of Iterating over values of iterable objects Values Arrays, strings, Map, Set
What types of for loops do you know in JavaScript… - sobes.tech