Conditional Statements - Exercise 3

A guard clause handles an invalid or early-exit case before the main path continues.

javascript

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.

javascript

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.

javascript

const score = 82;
const result = score >= 50 ? "Pass" : "Retry";
console.log(result); // Pass

The right side of && runs only when the left side is truthy.

javascript

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.

javascript

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.

javascript

const items = [];
if (items.length) console.log("Has items");
else console.log("Empty"); // Empty

Use parentheses to make the intended grouping visible when combining && and ||.

javascript

const hasTicket = true;
const isStaff = false;
const canEnter = hasTicket && (isStaff || true);
console.log(canEnter); // true

Early returns and guard clauses reduce indentation, making the normal path easier to read and test.

javascript

function canPublish(post) {
  if (!post) return false;
  if (!post.title) return false;
  return post.published === true;
}

Use switch when one value is compared with several fixed cases. Include break when a matching case should stop the next cases from running.

javascript

switch (role) {
  case 'admin':
    showAdminPanel();
    break;
  default:
    showHome();
}

Store a repeated condition in a clearly named boolean when it represents a meaningful rule. This keeps the decision readable and easier to change.

javascript

const isEligible = age >= 18 && hasId;
if (isEligible) {
  allowEntry();
}
All sections expanded. Activate the control to collapse all sections.