NelsonLabs
JavaScript Basics/If/Else & Conditionals

If/Else & Conditionals

Conditionals let your code make decisions. They're the first step toward writing logic that responds to different situations.

if / else if / else
javascript
const score = 78;

if (score >= 90) {
  console.log("A — Excellent");
} else if (score >= 75) {
  console.log("B — Good");
} else if (score >= 60) {
  console.log("C — Pass");
} else {
  console.log("F — Try again");
}
// Output: B — Good

// Simple if without else
const isLoggedIn = true;
if (isLoggedIn) {
  showDashboard();
}
Ternary operator — one-line conditionals
javascript
// condition ? valueIfTrue : valueIfFalse
const age = 20;
const status = age >= 18 ? "adult" : "minor";
// "adult"

// Great for JSX and template literals
const greeting = isLoggedIn ? "Welcome back!" : "Please log in";

// Can be nested (but keep it readable)
const grade = score >= 90 ? "A" : score >= 75 ? "B" : score >= 60 ? "C" : "F";
switch statement — clean multi-branch logic
javascript
const day = "Monday";

switch (day) {
  case "Monday":
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
  case "Friday":
    console.log("Weekday");
    break;  // without break, execution falls through to next case
  case "Saturday":
  case "Sunday":
    console.log("Weekend");
    break;
  default:
    console.log("Unknown day");
}

NOTE

Truthy and Falsy values. In JavaScript, every value is either truthy or falsy in a boolean context. Falsy values: false, 0, "", null, undefined, NaN. Everything else is truthy. This means if (username) checks whether the username is non-empty without explicitly comparing to an empty string.