if / else and ternary
Making decisions in code — if/else and the shortcut ? : form.
Step 1
The idea
Every decision in code is an if/else. Literally every one.
"If the button is visible, click it. Otherwise, log an error." That's an if/else. "If the user is logged in, show the dashboard. Otherwise, redirect to login." Same structure.
The syntax in JavaScript mirrors how you think in English — once you see it, you can't unsee it.
Step 2
See it run
Score: 82
Grade: B
Result: PASS
Quick result: PASSconst score = 82;
// Basic if/else
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
// You can also store the result in a variable
let result;
if (score >= 60) {
result = "PASS";
} else {
result = "FAIL";
}
console.log("Result:", result);
// Ternary — a one-line shortcut for simple if/else
const quickResult = score >= 60 ? "PASS" : "FAIL";
console.log("Quick result:", quickResult);$ node if-else.jsThe ternary reads as: condition ? value-if-true : value-if-false
Step 3
Now you try
Change score to 55 and predict the output before running. Then try 92.
Bonus: write a ternary that checks if a username has more than 3 characters and returns "valid" or "too short":
const username = "QA";
// write your ternary hereStep 4
Why a tester cares
if/else decisions appear in every real program. Here's a simple shipping cost calculator — the kind of logic that's inside every e-commerce site:
function getShippingCost(orderTotal, isMember) {
if (isMember && orderTotal >= 500) {
return 0; // free shipping for members with big orders
} else if (isMember) {
return 49; // discounted shipping for members
} else if (orderTotal >= 1000) {
return 0; // free shipping for large non-member orders
} else {
return 99; // standard shipping
}
}
console.log(getShippingCost(600, true)); // 0
console.log(getShippingCost(200, true)); // 49
console.log(getShippingCost(1200, false)); // 0
console.log(getShippingCost(300, false)); // 99$ node shipping.jsNotice how each if / else if / else branch handles one specific case. That clear structure is what makes code readable and maintainable.
Recap
- 1if/else runs different code depending on whether a condition is true or false.
- 2else if lets you chain multiple conditions — JS picks the first matching branch.
- 3Ternary (condition ? a : b) is a one-line shortcut — use it for simple true/false swaps.
Up next
Lesson 1.9 — for loops