Conditionals
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
A program does not have to run every line. An if statement tests a condition, a comparison that gives true or false, and runs its block only when the answer is true. Follow a ten-line script that picks what to wear from the temperature, run three times so the if, the else if and the else each get their turn.
5 أسئلة سريعة
اختر إجابة لتعرف السبب. تُحفَظ نتيجتك مع تقدّمك.
01What does the comparison 18 > 25 give?
A comparison always gives a boolean. 18 is not greater than 25, so the answer is false.
02In wear.js, temp is 30. Which lines run?
30 > 25 is true, so the block on line 4 runs. The else if and else are skipped, and the engine goes straight to line 10.
03When temp is 30, is the condition temp > 10 on line 5 checked?
Conditions are checked from the top down. Once one is true and its block runs, the following else if and else parts are skipped entirely.
04What does the script print when line 1 is let temp = 25;?
> means strictly greater. 25 > 25 is false, then 25 > 10 is true, so wear becomes "jacket".
05Why is === usually preferred to ==?
Strict equality (===) compares without converting types, which avoids surprises such as 0 == "" being true.
المسرد
- Conditional
- Code that runs only when a condition is true, written with if, else if and else.
- Condition
- The test in round brackets after if, such as temp > 25. JavaScript turns its value into true or false.
- Boolean
- A value that is either true or false. Every comparison gives one.
- Block
- The lines between curly braces { and }. An if runs its block only when its condition is true.
- else if
- Another test, checked only when every test above it was false. It is simply else followed by another if.
- else
- The block with no condition that runs when every test above it was false.
- Strict equality (===)
- Compares two values without converting their types; !== is its opposite.
- Falsy
- A value that counts as false in a condition: false, 0, -0, 0n, "", null, undefined and NaN.
الملاحظات والمصادر
- JavaScript has no elseif keyword. else if is simply else followed by another if statement, which is why you can chain as many as you need.
- If a block holds a single statement, the curly braces may be left out, but MDN recommends always using them: it is easier to read and safer when you add a line later.
- The condition does not have to be a comparison. JavaScript turns any value into true or false: false, 0, -0, 0n, "" (empty text), null, undefined and NaN count as false ("falsy"); every other value counts as true.
- let wear; declares the variable without a value, so it starts as undefined. Each block then gives it one; if no block ran (there is always an else here, so one does), it would still be undefined.
- The script is real. Save it as wear.js and run node wear.js, or paste it into the browser console. Change the number on line 1 to try another temperature.
اختبار يتاح بعد الخطوة الأخيرة.