Suggest an editImprove this articleRefine the answer for “Types of loops in JS”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**JavaScript has six main ways to organize a loop:** `for`, `while`, `do...while`, `for...in`, `for...of`, and the array method `forEach()`. **Key point:** `for...in` iterates over an object's keys, while `for...of` iterates over the values of iterable structures (arrays, strings, `Set`, `Map`).Shown above the full answer for quick recall.Answer (EN)Image## 1. `for`: the classic loop > Used when **the number of iterations is known in advance**. ```javascript for (let i = 0; i < 5; i++) { console.log(i); } ``` Result: ```javascript 0 1 2 3 4 ``` Structure: ```javascript for (initialization; condition; step) { // loop body } ``` - `initialization` runs once at the start - `condition` is checked before every iteration - `step` runs after every iteration --- ## 2. `while`: a pre-condition loop > Runs **while the condition is true**. ```javascript let i = 0; while (i < 5) { console.log(i); i++; } ``` Used when the number of iterations is **not known in advance**. --- ## 3. `do...while`: a post-condition loop > Guaranteed to run **at least once**. ```javascript let i = 5; do { console.log(i); i++; } while (i < 5); ``` Result: ```javascript 5 ``` > The loop body runs first, > then the condition is checked. --- ## 4. `for...in`: iterating over **an object's keys** > Used to walk through **an object's properties**. ```javascript const user = { name: 'Oleh', age: 25, city: 'Kyiv' }; for (let key in user) { console.log(key, ':', user[key]); } ``` Result: ```javascript name : Oleh age : 25 city : Kyiv ``` Features: - It iterates over **all enumerable properties**, including inherited ones. - It does not guarantee order. - It is better **not to use it for arrays**. --- ## 5. `for...of`: iterating over **iterable objects** > Ideal for **arrays, strings, Set, Map, and so on**. ```javascript const numbers = [10, 20, 30]; for (let num of numbers) { console.log(num); } ``` Result: ```javascript 10 20 30 ``` It also works with a string: ```javascript for (let char of 'JS') { console.log(char); } ``` > It iterates over values, not keys (unlike `for...in`). --- ## 6. `forEach()`: an array method > Not an operator, but an **array method**, > though it does the same job: iteration. ```javascript const arr = ['a', 'b', 'c']; arr.forEach((value, index) => { console.log(index, value); }); ``` Result: ```javascript 0 a 1 b 2 c ``` Features: - You cannot use `break` or `continue`. - It is convenient for **iterations without an early exit**.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.