while loops · حلقات while
while repeats
while (test) { ... }runs again and again, as long as the test staystrue.- It checks the test before each pass — so the body might run zero times.
while يكرر
while (test) { ... }تشغّل مراراً وتكراراً، طالما يبقى الاختبارtrue.- تفحص الاختبار قبل كل دورة — لذا قد تشغّل الجسم صفراً مرة.
let n = 1;
while (n <= 3) {
console.log(n); // → 1, then 2, then 3
n++;
}
Make progress every pass
- Something inside must move the test toward
false. - If nothing changes, the loop never stops — an infinite loop (the Stop button saves you).
تحرك في كل دورة
- شيء ما داخلها يجب أن يقود الاختبار نحو
false. - إذا لم يتغير شيء، لن تتوقف الحلقة أبداً — حلقة لا نهائية (زر التوقف ينقذك).
let n = 1;
while (n < 50) {
n = n * 2; // 2, 4, 8, 16, 32, 64 — then stop
}
console.log(n); // → 64
Each pass doubles n · كل دورة تضاعف n
while re-checks its test each pass. n must change, or it runs forever. · while يعيد اختبار شرطها في كل دورة. n يجب أن يتغير، أو ستستمر إلى ما لا نهاية.
Common mistakes
- Change the condition inside the loop, or it runs forever.
- A
whilechecks its condition first, so it may run zero times.
أخطاء شائعة
- غير الشرط داخل الحلقة،否则会运行永远。
- A
whileيتحقق من شرطه أولاً، لذا قد تشغّل صفراً مرة.
Now you try
- Use a
whileloop. - Press Check answer to test it.
الآن جرب بنفسك
- استخدم حلقة
while. - اضغط على تحقق من الإجابة لاختبارها.
let n = 3. Use a while loop to count down: log 3, 2, 1, one per line. · let n = 3. استخدم حلقة while للعد تنازلياً: أخرج 3، 2، 1، واحدة في كل سطر.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
let n = 1. While n is 16 or less, log n then double it. Output should be 1, 2, 4, 8, 16. · let n = 1. طالما أن n يساوي 16 أو أقل، سجل n ثم ضاعفها. يجب أن يكون المخرج 1، 2، 4، 8، 16.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Use a while loop to add up 1 to 4, then log the total (it is 10). · استخدم حلقة while لجمع 1 إلى 4، ثم أخرج المجموع (وهو 10).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.