Conditionals: if, switch & ternary

How to make your code think and make decisions using if statements, switch cases, and the concise ternary operator.

JavaScript6 min readConcept 9 of 62

What are conditionals?

Conditionals are the foundation of logic in programming. They allow your code to execute different instructions based on whether a specific condition is true or false.

Without conditionals, a program would just run straight from top to bottom every single time.

When to use which?

Use if...else if...else for complex logic, checking ranges (like age > 18), or combining multiple boolean conditions.

Use switch when checking a single variable against many specific, discrete values (like evaluating a status string).

Use the ternary operator (? :) for quick, single-line assignments, such as determining a button's color based on an isActive boolean.

Syntax overview

if (condition) { ... }: The block runs only if the condition evaluates to a truthy value.

switch (value) { case x: ... break; }: The switch checks if value === x. It requires the break keyword, otherwise it will 'fall through' and execute the next case too!

condition ? trueResult : falseResult: The ternary operator evaluates the condition. If truthy, it returns the left side of the colon; if falsy, it returns the right side.

Branching Logic

Select a user role to see how an if / else if, a switch, and a ternary would evaluate it and branch the code execution.

Branching Logic

Set the user's role

const role = "admin";
// 1. The if/else if approach
if (role === "admin") {
console.log("Full access");
} else if (role === "editor") {
console.log("Edit access");
} else {
console.log("Read only");
}
// 2. The switch approach
switch (role) {
case "admin":
grantFullAccess();
break;
case "editor":
grantEditAccess();
break;
default:
grantReadOnlyAccess();
}
Execution flow highlighted in code pane
iThe if/else approach evaluates conditions sequentially from top to bottom. The switch approach jumps straight to the matching case using strict equality.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens if you omit the `break` statement in a `switch` case?
  2. 2Which statement uses strict equality (`===`) under the hood to compare values?
  3. 3What is the result of `const status = true ? 'Active' : 'Inactive';`?

Remember this

  • if statements evaluate whether a condition is truthy or falsy.
  • switch statements use strict equality (===) and require a break to prevent fall-through.
  • The ternary operator (? :) is a concise way to assign a value based on a condition.

Done with this concept?

Mark it complete to track your progress. No login needed.