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")، ولا تستخدم ever علامة=واحدة.
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. · اضغط تشغيل لرؤية المخرجات هنا.