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. - אם אין שינוי, הלולאה לעולם לא תפסיק — זוהי לולאה אינסופית (הכפתור Stop יציל אותך).
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.
טעויות נפוצות
- שנה את התנאי בתוך הלולאה, או שתפעל לנצח.
- לולאת
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. · לחץ על הרץ כדי לראות את התוצא כאן.