Sobes.tech
Junior — Middle

Can you list the existing types of loops in JavaScript?

sobes.tech AI

Answer from AI

In JavaScript, the following main types of loops exist:

  • for — a classic loop with initialization, condition, and step.
for (let i = 0; i < 5; i++) {
  console.log(i);
}
  • while — executes the loop body as long as the condition is true.
let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}
  • do...while — executes the body first, then checks the condition.
let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);
  • for...in — iterates over the enumerable properties of an object.
const obj = {a: 1, b: 2};
for (let key in obj) {
  console.log(key, obj[key]);
}
  • for...of — iterates over iterable objects (arrays, strings, etc.).
const arr = [10, 20, 30];
for (let value of arr) {
  console.log(value);
}

Each of these loops is suitable for different tasks depending on the data structure and logic.

Can you list the existing types of loops in… - sobes.tech