Sobes.tech
Junior

What cycle constructs exist in JavaScript?

sobes.tech AI

Answer from AI

  • for: Repeats a block of code a fixed number of times.
    for (let i = 0; i < 5; i++) {
      console.log(i);
    }
    
  • for...in: Iterates over the properties of an object (including inherited ones if not filtered).
    const obj = { a: 1, b: 2 };
    for (const key in obj) {
      console.log(key + ': ' + obj[key]);
    }
    
  • for...of: Iterates over iterable objects (arrays, strings, Map, Set, etc.).
    const arr = [1, 2, 3];
    for (const element of arr) {
      console.log(element);
    }
    
  • while: Repeats a block of code while the condition is true.
    let i = 0;
    while (i < 5) {
      console.log(i);
      i++;
    }
    
  • do...while: Executes the block of code once, then repeats it while the condition is true. The condition is checked at the end.
    let i = 0;
    do {
      console.log(i);
      i++;
    } while (i < 5);
    
  • forEach (method of arrays and other iterable objects): Executes a provided function once for each element.
    const arr = [1, 2, 3];
    arr.forEach(function(element) {
      console.log(element);
    });
    
What cycle constructs exist in JavaScript? — QA / QA… - sobes.tech