What types of loops exist in JavaScript and how do they work?
sobes.tech AI
Answer from AI
In JavaScript, the following main types of loops exist:
-
for: Executes a block of code a certain number of times. Used when the number of iterations is known. Consists of three optional expressions: initialization, condition, and final expression.for (let i = 0; i < 5; i++) { // Loop body console.log(i); } -
while: Executes a block of code as long as the specified condition is true. Used when the number of iterations is unknown in advance.let i = 0; while (i < 5) { // Loop body console.log(i); i++; } -
do...while: Similar towhile, but the condition is checked after the loop body is executed. Guarantees that the loop body is executed at least once.let i = 0; do { // Loop body console.log(i); i++; } while (i < 5); -
for...in: Iterates over the enumerable properties of an object. Iterates over the object's keys.const obj = { a: 1, b: 2, c: 3 }; for (const key in obj) { // Working with key and value: obj[key] console.log(`${key}: ${obj[key]}`); } -
for...of: Iterates over the values of iterable objects (such as arrays, strings, Map, Set). Iterates over the values.const arr = [1, 2, 3]; for (const value of arr) { // Working with value console.log(value); } -
forEach(array method): Executes a provided function once for each array element. Not a traditional control loop in syntax, but performs the same task of iterating over elements.const arr = [1, 2, 3]; arr.forEach(function(value, index, array) { // Working with value, index, and array reference console.log(`${index}: ${value}`); });