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
}
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.
Doubled after 8 months: Rs 2143.59 Attempt 1 Attempt 2
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#
Learning HTML Learning CSS Learning JavaScript H i !
for...in - every key of an object#
maths -> 92 science -> 85 english -> 78
break and continue#
4 7 9
Nested loops#
A loop inside a loop - the inner loop runs completely for every turn of the outer loop.
Summary#
forwhen you know the count;whilewhen you repeat until something happens;do...whileruns at least once.for...offor array/string values,for...infor object keys.breakexits the loop,continueskips to the next turn.- Avoid infinite loops - the condition must eventually become false.