Lesson 12 / الدرس 12

Repeating: the while loop / التكرار: حلقة while

The third thing a program can do. A while loop is the simplest form and the one that shows the machinery clearly — including the mistake that freezes the browser.

الثالث مما يستطيعه البرنامج. وحلقة while أبسط صيغة وهي التي تُظهر الآلة بوضوح — بما فيه الخطأ الذي يجمّد المتصفح.

let count = 1;                 1. start somewhere
while (count <= 5) {           2. a condition, checked EVERY time round
  console.log(count);
  count = count + 1;           3. something that moves towards the end
}
Every loop has those three parts, in every language. Leave out the third and the condition never becomes false — the loop runs forever and the page stops responding. Run the demonstration.

When while is the right loop

You knowUse
Exactly how many timesfor — lesson 13
Only a condition to stop atwhile
You must run at least oncedo … while
You are going through a listfor … of — lesson 15

The second row is where while earns its place: reading until there is nothing left, retrying until something succeeds, keeping going until a total is reached. You do not know the count in advance, and a for loop would be pretending you did.

Off by one

The commonest loop bug is running one time too many or too few, and it comes down to < against <=. Starting at 1, while (i <= 5) runs five times; while (i < 5) runs four. Starting at 0, it is the other way round. Rather than reasoning about it, run the loop with a small number and count the output — it takes ten seconds and is never wrong.

Try it live / جرّب بنفسك

Preview / المعاينة

Check yourself / اختبر نفسك

1. What are the three parts every loop needs?

2. When is while a better choice than for?

3. What happens when a loop never ends?

Your task / مهمتك

Use a while loop for something whose length you genuinely cannot know in advance: keep halving a number until it drops below one and count the steps, or keep adding items to a basket until a budget is spent. Print each round so the progress is visible. Then write a loop that would run forever, protect it with a guard counter, and explain which of the three parts was missing.

استخدم حلقة while لشيء لا تستطيع معرفة طوله مسبقًا فعلًا: كأن تنصّف رقمًا حتى ينزل تحت الواحد وتعدّ الخطوات، أو تضيف أصنافًا إلى سلة حتى تُنفق ميزانية. واطبع كل دورة ليكون التقدم مرئيًا. ثم اكتب حلقة كانت ستعمل إلى الأبد، واحمها بعدّاد حراسة، واشرح أي الأجزاء الثلاثة كان مفقودًا.

  • A loop whose count is genuinely unknown in advance حلقة عددها غير معروف مسبقًا فعلًا
  • Every round printed كل دورة مطبوعة
  • A runaway loop, made safe with a guard حلقة جامحة مؤمَّنة بحارس
  • Which of the three parts was missing, named أي الأجزاء الثلاثة كان مفقودًا، مسمّى
How do you want to submit? / كيف تريد التسليم؟