if / else
Making decisions
if (test) { ... }runs its block only when the test istrue.elsegives the path to take when the test isfalse.
קבלת החלטות
if (test) { ... }מפעיל את הבלוק שלו רק כאשר הבדיקה היאtrue.elseקובעת את הדרך ללכת כאשר הבדיקה היאfalse.
let age = 20;
if (age >= 18) {
console.log("adult"); // → adult
} else {
console.log("minor");
}
Many paths with else if
- Add
else iffor more choices. JavaScript checks each test top to bottom. - The first test that is
truewins; the rest are skipped.
מספר דרכים עם else if
- הוסף
else ifעבור אפשרויות נוספות. JavaScript בודק כל בדיקה מלמעלה למטה. - הבדיקה הראשונה שהיא
trueזוכה; שאר הבדיקות מושתקות.
let mark = 72;
if (mark >= 70) {
console.log("A"); // → A
} else if (mark >= 50) {
console.log("B");
} else {
console.log("C");
}
Which branch runs? · איזה ветка תופעל?
Tests are checked top-down; the first true one runs and the rest are skipped. · המבחנים נבדקים מלמעלה למטה; הראשון הנכון פועל והיתר מוותרים.
Watch out
- Put the test in
( )and the block in{ }. - Inside a test, compare with
===(day === "Sat"), never a single=.
שימו לב
- הנח את הבדיקה ב-
( )והבלוק ב-{ }. - בתוך בדיקה, השוו עם
===(day === "Sat"), לעולם לא עם ⟨=⟩ יחיד.
Common mistakes
- The condition goes in
( )and the body in{ }. - Compare with
===.
טעויות נפוצות
- התנאי נמצא ב-
( )והגוף ב-{ }. - השווה ל
===.
Now you try
- Read the value, then choose with
if/else. - Press Check answer to test it.
כעת תנסו בעצמכם
- קרא את הערך, ולאחר מכן בחר עם
if/else. - לחץ על בדיקת תשובה כדי לבדוק אותה.
let n = 5. If n is greater than 0 log positive, otherwise log not positive. (It should log positive.) · let n = 5. אם n גדול מ-0 הדפס positive, אחרת הדפס not positive. (צריך להדפיס positive.)
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
let mark = 65. Log A for 70 or more, B for 50–69, and C for less. (It should log B.) · let mark = 65. הדפס A עבור 70 ומעלה, B עבור 50–69, ו-C לעומת זאת. (צריך להדפיס B.)
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
let n = 4. Log even if n % 2 === 0, otherwise log odd. (It should log even.) · let n = 4. הדפס even אם n % 2 === 0, אחרת הדפס odd. (צריך להדפיס even.)
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.