Conditional Statements - Exercise 3
A guard clause handles an invalid or early-exit case before the main path continues.
function greet(name) {
if (!name) return "Missing name";
return `Hello, ${name}`;
}
console.log(greet("Ada"));Each case is compared with strict equality, and break prevents fall-through.
const role = "editor";
switch (role) {
case "editor": console.log("Can edit"); break;
default: console.log("Read only");
}Use a ternary for a short choice between two values, rather than for multiple statements or deeply nested logic.
const score = 82;
const result = score >= 50 ? "Pass" : "Retry";
console.log(result); // PassThe right side of && runs only when the left side is truthy.
const isOnline = true;
isOnline && console.log("Connected");Check the most specific or highest-priority condition first so a broader condition does not match too early.
const temperature = 38;
if (temperature >= 40) console.log("Extreme");
else if (temperature >= 30) console.log("Hot");
else console.log("Mild");A falsy value makes the condition fail, so JavaScript executes the else branch when one exists.
const items = [];
if (items.length) console.log("Has items");
else console.log("Empty"); // EmptyUse parentheses to make the intended grouping visible when combining && and ||.
const hasTicket = true;
const isStaff = false;
const canEnter = hasTicket && (isStaff || true);
console.log(canEnter); // trueEarly returns and guard clauses reduce indentation, making the normal path easier to read and test.
function canPublish(post) {
if (!post) return false;
if (!post.title) return false;
return post.published === true;
}