JavaScriptbeginner 7 min
Run different code depending on a condition using if, else and comparison operators.
How to compare values, and how to run code only when a condition is true.
Programs constantly decide things: is the password right, is the cart empty, is it past midnight. if is how code chooses a path.
A condition is something that is either true or false. Comparisons produce conditions:
=== equal to, !== not equal to> greater than, < less than, >=, <=An if statement runs its block only when the condition is true. Add else for the other case, and else if for more choices.
You can combine conditions: && means AND (both must be true), || means OR (at least one), ! means NOT.
temperature is 28.Nice weather.else is skipped because an earlier branch ran.17 >= 18 (false) AND true. AND needs both, so it prints false.Change temperature to 35, then to 10, and run each time. Which message appears?
= instead of ===. = assigns, === compares."5" === 5 is false because the types differ.true/false conditions.if, else if, else choose which block runs.&&, ||, !.Next: repeating work with loops.
if (condition) {
// runs when true
} else {
// runs when false
}const temperature = 28;
if (temperature > 30) {
console.log("It's hot. Drink water.");
} else if (temperature >= 20) {
console.log("Nice weather.");
} else {
console.log("Bring a jacket.");
}
const age = 17;
const hasTicket = true;
console.log(age >= 18 && hasTicket);