Conditionals
Conditionals let a program make decisions: show a discount only to members, give a grade based on marks, or warn when an M-Pesa balance is too low. JavaScript offers if, else if and else, the compact ternary operator, and the switch statement.
if and else
An if statement runs a block of code only when its condition is truthy. The condition goes in round brackets and the block in curly braces. An optional else block runs otherwise.
const balance = 350;
const fare = 100;
if (balance >= fare) {
console.log("Fare paid. Safe journey!");
} else {
console.log("Insufficient balance. Please top up.");
}
else if: choosing between several options
Chain conditions with else if. JavaScript checks them from top to bottom and runs only the first block whose condition is true; the rest are skipped.
const marks = 67;
let grade;
if (marks >= 80) {
grade = "A";
} else if (marks >= 65) {
grade = "B";
} else if (marks >= 50) {
grade = "C";
} else {
grade = "Fail";
}
console.log(`Marks: ${marks}, grade: ${grade}`);
Because 67 is not at least 80, the first test fails; 67 is at least 65, so grade becomes "B" and the remaining tests are never checked. Order matters: if you tested marks >= 50 first, a score of 90 would wrongly get a C. Try changing marks to 85, 50 and 12 in the editor.
Combining and simplifying conditions
Use the logical operators to combine tests: if (age >= 18 && hasId) or if (day === "Sat" || day === "Sun"). Conditions use truthiness, so you can write short checks:
const username = "";
const cart = [];
if (!username) {
console.log("Please enter your name");
}
if (cart.length === 0) {
console.log("Your cart is empty");
}
An empty array or object is truthy, so if (cart) is true even when the cart has nothing in it. Check cart.length === 0 instead. Also, never use a single = in a condition: if (marks = 50) assigns 50 and is always truthy. Use ===.
The ternary operator
For a simple "this or that" value, the conditional (ternary) operator fits on one line: condition ? valueIfTrue : valueIfFalse.
const age = 17;
const message = age >= 18 ? "You can vote" : "Too young to vote";
console.log(message);
const items = 1;
console.log(`You have ${items} item${items === 1 ? "" : "s"}`);
The ternary is an expression, so it can sit inside a template literal or an assignment. Keep it for short choices; nesting several ternaries becomes hard to read, and a normal if is clearer.
switch
When one value is compared against many fixed options, switch can be tidier than a long else if chain. Each case is compared using strict equality (===), and default runs if nothing matches.
const day = "Sat";
switch (day) {
case "Sat":
case "Sun":
console.log("Weekend: no classes");
break;
case "Fri":
console.log("Last school day of the week");
break;
default:
console.log("A normal school day");
}
Stacking case "Sat": and case "Sun": lets both values share one block. The break statement jumps out of the switch.
Forgetting break causes fall-through: after a match, JavaScript keeps running the following cases until it meets a break or the end.
const level = 1;
switch (level) {
case 1:
console.log("Beginner");
case 2:
console.log("Intermediate");
break;
case 3:
console.log("Advanced");
}
Because switch uses ===, switch ("1") will not match case 1: a string never equals a number. Convert form input first. Also, switch is for exact values; for ranges such as marks between 65 and 79, use if/else if.
Key points
ifruns a block when its condition is truthy;else ifandelsehandle the other cases.- Only the first matching branch runs, so order your conditions carefully.
- Empty arrays and objects are truthy; use
===, never=, in conditions. - The ternary
a ? b : cpicks between two values in one expression. switchcompares one value with===; rememberbreakto avoid fall-through.
Tip: use the ← and → keys to move between pages.
