Lesson 4
18 min
if, else, else if and the ternary operator for making decisions.
Definition
A conditional structure is a statement that lets a program choose which code to run depending on the result of a condition, that is, an expression that evaluates to true orfalse. In JavaScript, the main conditional structures areif / else, the ternary operator andswitch.
Conditional structures let a program make decisions: run a block of code only if a condition is true, or run another block otherwise. This is a fundamental concept of programming: without conditions, a program would just run through the same instructions, never adapting to the context.
In JavaScript, the main ways of writing conditions areif / else, the ternary operator, and theswitch statement.
You make conditional decisions every day: "if it rains, I take an umbrella, otherwise I leave without one". A program works in exactly the same way. A web page can thus display a welcome message if the user is logged in, or a login form otherwise; a game can display "You won!" or "You lost!" depending on the score.
The simplest form is a standalone if: the block between curly braces only runs if the condition is true. Otherwise, the program simply moves on to what comes next.
const temperature = 32;
if (temperature > 30) {
console.log("It's very hot, remember to stay hydrated!");
}
console.log("End of the program"); // displayed in all casesTo handle several cases, chain withelse if andelse:
const hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
// → "Good afternoon!"if: runs its block if the condition in parentheses is true (true).else if: adds an extra condition, tested only if the previous one is false.else: runs only if none of the previous conditions is true.else if as needed, but beyond 3 or 4, a switch is often more readable.As soon as one of the conditions is true, JavaScript runs its block thenignores the rest of the chain: the order of the conditions is therefore important. Always put the most specific cases first.
A condition can also combine several logical operators seen in the previous lesson:
const age = 20;
const hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("Access granted");
} else {
console.log("Access denied");
}You can place an if inside another one. This is sometimes necessary, but it is better to limit this nesting, which quickly makes the code hard to follow. Often, a logical operator can achieve the same result in a more readable way.
const isLoggedIn = true;
const isAdmin = false;
// Nested version
if (isLoggedIn) {
if (isAdmin) {
console.log("Admin panel");
} else {
console.log("Member area");
}
} else {
console.log("Please log in");
}
// Flattened check for the admin case, using &&
if (isLoggedIn && isAdmin) {
console.log("Admin panel");
}For simple cases (a single alternative), theternary operator lets you write a condition very concisely. Its syntax is:condition ? valueIfTrue : valueIfFalse.
const age = 16;
const message = age >= 18 ? "Adult" : "Minor";
console.log(message); // "Minor"
// Also useful directly in a display:
const status = age >= 18 ? "Access granted" : "Access denied";The ternary operator is very handy, but it quickly becomes hard to read if you nest it several times. In that case, prefer a classicif / else or aswitch.
Its real strength is that it produces a value: you can assign it to a variable or insert it in a sentence, which anif does not allow directly.
const itemCount = 3;
console.log("You have " + itemCount + (itemCount > 1 ? " items" : " item"));
// → "You have 3 items"When you compare the same value against many possible cases,switch often makes the code more readable than a long series of else if.
const day = "tuesday";
switch (day) {
case "saturday":
case "sunday":
console.log("Weekend!");
break;
case "monday":
console.log("Start of the week, hang in there!");
break;
default:
console.log("Weekday.");
}
// → "Weekday."case is compared to the tested value using strict equality (===).break is essential: without it, execution continues into the next case (this is called "fall-through").default runs if no case matches — it is the equivalent of the final else.In the example, "saturday" and"sunday" deliberately share the same block: since there is no break after the firstcase, execution "falls" into the next one. This is the useful side of fall-through. Forgetting abreak by mistake, however, is a classic source of bugs:
const level = 1;
switch (level) {
case 1:
console.log("Beginner"); // displayed
case 2:
console.log("Intermediate"); // also displayed, for lack of a break!
break;
default:
console.log("Other");
}In JavaScript, a condition does not need to be a strict boolean: any value is automatically converted totrue orfalse when it is tested. We speak of"truthy" values (considered true) and"falsy" values (considered false).
// "Falsy" values (considered false):
// false, 0, "", null, undefined, NaN
if (0) {
console.log("Never displayed");
}
if ("") {
console.log("Never displayed either");
}
// Everything else is "truthy" (considered true)
if ("Hello") {
console.log("Displayed: a non-empty string is truthy");
}Understanding this mechanism lets you write shorter conditions, for example to check that a variable actually has a value before using it:
const username = "";
if (username) {
console.log("Welcome,", username);
} else {
console.log("Username missing");
}
// → "Username missing" (because an empty string is falsy)Be careful: this shortcut can trip you up. The number0 is falsy, even though it can be a perfectly valid value (a score of zero, for example). In that case, compare explicitly rather than relying on automatic conversion:
const score = 0;
if (score) {
console.log("Score:", score); // not displayed, even though 0 is valid!
}
if (score !== undefined) {
console.log("Score:", score); // displayed correctly
}Best practices
Give explicit names to your booleans (isLoggedIn,hasAccess) so that the condition reads like a sentence. Handle error cases or simple cases first, then the main case: the code stays flat and easier to reread.
= instead of === in a condition: if (age = 18) assigns the value instead of comparing it.break in a switch and triggering several cases unintentionally.else if badly: a broad condition placed first prevents the following ones from ever being tested.prompt() input (text) to a number with === without converting it first.Exercise 1: even, odd and days
In a new JavaScript file:
number containing an integer of your choice.if / else condition that displays "even" or "odd" depending on the value (use the % operator).switch that displays the name of the day corresponding to a number from 1 (Monday) to 7 (Sunday).Exercise 2: grade and access
Declare a variable grade (between 0 and 20) and display a rating with if / else if / else: "Excellent" from 16, "Very good" from 14, "Good" from 12, "Satisfactory" from 10, and "Insufficient" below that.
Bonus: declare age and hasInvitation, then display "Entry allowed" only if the person is at least 18 years oldand has an invitation.
if / else if / else is the basic conditional structure, and the order of the conditions matters.switch is suited to comparing the same value against many cases; don't forget the break.false in a condition.=== to compare, and avoid overly deep nesting by combining conditions with && and ||.