Conditions
if runs code only when a condition is true. Add else if and else to handle other cases.
Conditions let your page react differently to different situations: show "Free delivery" only above a certain total, show an error if a field is empty, show a different greeting in the morning and evening. JavaScript checks the conditions in order and runs the first block that's true.
Anything inside the round brackets is turned into true or false. Besides comparisons, JavaScript treats some values as "falsy": 0, "" (empty string), null, undefined and NaN. So if (name) is a quick way to check that a name was typed.
Example
<!DOCTYPE html>
<html>
<body>
<label>Cart total (Rs): <input id="total" type="number" value="450"></label>
<button onclick="check()">Check delivery</button>
<p id="out"></p>
<script>
function check() {
const total = Number(document.getElementById("total").value);
let message;
if (total >= 500) {
message = "Free delivery!";
} else if (total >= 200) {
message = "Add Rs " + (500 - total) + " more for free delivery.";
} else {
message = "Minimum order is Rs 200.";
}
document.getElementById("out").textContent = message;
}
</script>
</body>
</html>▶ Try it yourselfCombine conditions with && (and), || (or) and ! (not).
Example
if (isLoggedIn && cartCount > 0) {
showCheckoutButton();
}Key points
if/else if/elsechoose what code runs.- Combine with
&&,||,!. - Empty strings, 0, null and undefined count as false.
📝 Test yourself
1. When does the else block run?
2. Which operator means "and"?
3. Fill in the keyword that starts a condition:
(age >= 18) { ... }
