Skip to main content

Types of loops in JS

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.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.