JavaScript Loops

A loop repeats a block of code many times, so you do not write the same line again and again.


for loop

for (let i = 1; i <= 5; i++) {
  console.log(i);
}
Output of the above program is

1
2
3
4
5

The for has three parts: start (let i = 1), condition (i <= 5) and step (i++).


while and do while

let n = 3;
while (n > 0) {
  console.log(n);
  n--;
}

let x = 10;
do {
  console.log("Runs once, x =", x);
} while (x < 5);
Output of the above program is

3
2
1
Runs once, x = 10

while checks the condition first. do while runs the block at least once, and then checks.


for…of (arrays and strings)

const fruits = ["apple", "banana", "mango"];

for (const fruit of fruits) {
  console.log(fruit);
}
Output of the above program is

apple
banana
mango


for…in (object keys)

const user = { name: "Robin", age: 25 };

for (const key in user) {
  console.log(key + ": " + user[key]);
}
Output of the above program is

name: Robin
age: 25


break and continue

for (let i = 1; i <= 6; i++) {
  if (i === 3) continue;   // skip 3
  if (i === 5) break;      // stop at 5
  console.log(i);
}
Output of the above program is

1
2
4

Note: Make sure the condition becomes false at some time. A loop that never ends (an infinite loop) freezes the browser tab.

Summary

  • for is for a known number of rounds, while for an unknown number.
  • for...of loops over values, for...in over object keys.
  • break stops the loop, continue skips one round.
  • Next: JavaScript Functions.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.