Conditionals
Teach your programs to make decisions using if/else, comparison and logical operators, the ternary shortcut, switch statements, and JavaScript's quirky truthy/falsy rules.
Every interesting program makes choices. Should we show the dashboard or the login screen? Is the user old enough to proceed? Did the password match? Without the ability to make decisions, a program can only do the exact same thing every time — which makes it pretty useless in the real world.
In JavaScript, conditionals are the tool that lets your code look at a situation and choose a path. By the end of this lesson you will be comfortable writing if/else statements, chaining multiple conditions, using the handy ternary operator as a one-liner, reaching for switch when you have many fixed cases, and understanding why some values in JavaScript are treated as "truthy" or "falsy" even when they are not literally true or false.
#The if Statement — Your Program's First Decision
Conditionals are like traffic lights
Think of a conditional as a traffic light at an intersection. When you arrive, the light checks its timer and decides: green means go, red means stop. You do not always take the same action — the action depends on a condition that is checked in the moment. A JavaScript if statement works exactly the same way: it checks a condition, and runs a block of code only if that condition is true.
The simplest form is just if. If the condition inside the parentheses is true, the code inside the curly braces runs. If it is false, JavaScript skips the whole block and moves on.
const temperature = 28;
if (temperature > 25) {
console.log("It's warm outside!");
}
console.log("Program continues here.");#Adding an else — The Fallback Path
Often you want to do something different when the condition is false, not just skip it. That is where else comes in. The else block runs whenever the if condition is not true — think of it as the default path.
const hour = 14; // 2 PM in 24-hour time
if (hour < 12) {
console.log("Good morning!");
} else {
console.log("Good afternoon!");
}#else if — Handling More Than Two Cases
Real decisions often have more than two paths. What if the hour is in the evening? You can chain as many else if blocks as you need. JavaScript checks each condition from top to bottom and runs the first block whose condition is true, then skips the rest.
const hour = 20; // 8 PM
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}#Comparison and Logical Operators
Every condition is an expression that evaluates to true or false. You build those expressions with comparison operators and logical operators.
Comparison operators compare two values: - === — strictly equal (value AND type must match) - !== — strictly not equal - > — greater than - < — less than - >= — greater than or equal to - <= — less than or equal to
Logical operators combine conditions: - && (AND) — true only if both sides are true - || (OR) — true if at least one side is true - ! (NOT) — flips true to false and false to true
const age = 20;
const hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("Welcome to the show!");
} else {
console.log("Sorry, you can't enter.");
}=== vs == — always use triple equals
JavaScript has two equality operators: == (loose) and === (strict). The loose version tries to convert types before comparing, which leads to surprising results like 0 == false being true. Unless you have a specific reason, always use `===`. It checks both the value and the type, which is almost always what you want.
#Truthy and Falsy — When Non-Booleans Act Like Booleans
JavaScript conditions do not strictly require true or false. Every value in JavaScript is considered either truthy (behaves like true in a boolean context) or falsy (behaves like false). There are exactly six falsy values to memorize:
false0""(empty string)nullundefinedNaN
Everything else — including [], {}, any non-zero number, and any non-empty string — is truthy. This is frequently used as a shorthand.
const username = ""; // empty string — falsy!
if (username) {
console.log("Hello, " + username);
} else {
console.log("Please enter a username.");
}#The Ternary Operator — Conditionals in One Line
When you just want to pick between two values — not run a block of code — the ternary operator is a compact alternative to if/else. The syntax is:
`` condition ? valueIfTrue : valueIfFalse ``
The name "ternary" just means it takes three parts (the condition, the true value, and the false value). It is especially useful when assigning a value or building a string.
const score = 72;
const result = score >= 60 ? "Pass" : "Fail";
console.log(result);Keep ternaries simple
Ternaries shine for simple true/false value choices. If you find yourself nesting one ternary inside another, stop — reach for a regular if/else instead. Readability always wins over cleverness.
#switch — When You Have Many Exact Values to Check
When you need to compare one value against many specific options, a chain of else if blocks can get messy. The switch statement is designed exactly for this case. It takes an expression, then jumps to the matching case. The break keyword at the end of each case tells JavaScript to stop and exit the switch — without it, execution "falls through" to the next case, which is rarely what you want.
const day = "Wednesday";
switch (day) {
case "Monday":
console.log("Start of the work week.");
break;
case "Wednesday":
console.log("Halfway there!");
break;
case "Friday":
console.log("Almost the weekend!");
break;
default:
console.log("Just another day.");
}What will this code log? ```js const x = 0; if (x) { console.log("truthy"); } else { console.log("falsy"); } ```
You now have the full toolkit for making decisions in JavaScript. if/else if/else for general branching logic, the ternary operator for quick value choices, and switch for matching against a fixed list of known values. Pair these with your knowledge of comparison and logical operators, keep the falsy six in mind, and your programs can handle almost any decision the real world throws at them.
Key takeaways
- Use if / else if / else to run different code based on a condition — JavaScript checks each branch top to bottom and stops at the first match.
- Always use === for equality checks; the loose == operator can produce surprising results due to automatic type conversion.
- Only six values are falsy in JavaScript: false, 0, "", null, undefined, and NaN — everything else is truthy.
- The ternary operator (condition ? a : b) is a clean one-liner for choosing between two values, but avoid nesting them.
- Use switch when you are comparing one value against many fixed options — always add a break at the end of each case.
The lesson lists exactly six falsy values. What does this code log?
const username = "";
if (username) {
console.log("Hello, " + username);
} else {
console.log("Please enter a username.");
}This code has a bug — what's wrong?
const day = "Wednesday";
switch (day) {
case "Monday":
console.log("Start of the work week.");
case "Wednesday":
console.log("Halfway there!");
case "Friday":
console.log("Almost the weekend!");
default:
console.log("Just another day.");
}Complete the ternary so `result` is "Pass" when the score is 60 or higher, and "Fail" otherwise.
const score = 72; const result = score >= 60 "Pass" : "Fail"; console.log(result); // Pass
Arrange these lines into a getTicketPrice function that returns "Free" for ages under 5 and "$8" for ages 5–12, checking the smallest range first.
return "$8";
function getTicketPrice(age) {}
if (age < 5) { } else if (age <= 12) {}
return "Free";
Write a function called getTicketPrice that takes a person's age (a number) and returns their ticket price as a string. The rules are: children under 5 are free ("Free"), ages 5–12 pay $8 ("$8"), ages 13–64 pay $15 ("$15"), and seniors aged 65 or older pay $10 ("$10"). Call the function with a few different ages and log the results.
Try it live — edit the code and hit Run to see the output: