⚡0 XP🔥0

Loops

Lesson 3 of 7 ⏱ 3 min read ✎ 3 exercises ❓ 4-question quiz ▶ Runs JavaScript

Repeat work with for, while and do...while loops, for...of over arrays and strings, for...in over object keys, break and continue, and nested loops.

Why loops?#

A loop repeats code - print 100 receipts, check every student's marks, retry a password. Without loops you would copy the same line again and again.

The for loop#

for (start; condition; step) {
  // body
}
▶ Try it YourselfJavaScript
Ctrl + Enter to run
Output
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5
Sum of even numbers: 30
हिंदी में समझें

for loop के तीन हिस्से होते हैं: शुरुआत (let i = 1), शर्त (i <= 5 - जब तक सही है तब तक चलो), और बदलाव (i++ - हर चक्कर के बाद i को 1 बढ़ाओ)। Condition false होते ही loop रुक जाता है।

while and do...while#

Use while when you don't know in advance how many times to repeat.

▶ Try it YourselfJavaScript
Ctrl + Enter to run
Output
Doubled after 8 months: Rs 2143.59
Attempt 1
Attempt 2
Common Mistake

If the condition never becomes false, the loop runs forever and the page freezes. Make sure something inside the loop moves it towards the end (months++, balance = ...).

for...of - every value of an array or string#

▶ Try it YourselfJavaScript
Ctrl + Enter to run
Output
Learning HTML
Learning CSS
Learning JavaScript
H
i
!

for...in - every key of an object#

▶ Try it YourselfJavaScript
Ctrl + Enter to run
Output
maths -> 92
science -> 85
english -> 78

break and continue#

▶ Try it YourselfJavaScript
Ctrl + Enter to run
Output
4
7
9

Nested loops#

A loop inside a loop - the inner loop runs completely for every turn of the outer loop.

▶ Try it YourselfJavaScript
Ctrl + Enter to run

Summary#

  • for when you know the count; while when you repeat until something happens; do...while runs at least once.
  • for...of for array/string values, for...in for object keys.
  • break exits the loop, continue skips to the next turn.
  • Avoid infinite loops - the condition must eventually become false.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Multiplication table

Read a number n with prompt() and print its table from 1 to 10 in the format 7 x 1 = 7.

Test input:
7
Expected output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
2

Sum of digits

Read a whole number and print the sum of its digits using a while loop with % and Math.floor. For 90817 the answer is 25.

Test input:
90817
Expected output:
25
3

Star pyramid

Print this pattern of 4 rows using nested loops (or repeat). Each row has spaces then stars:

   *
  ***
 *****
*******
Expected output:
   *
  ***
 *****
*******

Quick Quiz

Q1.

How many times does for (let i = 0; i < 5; i++) run?

Q2.

Which loop is best for going through every item of an array?

Q3.

What does continue do?

Q4.

A do...while loop always runs its body...