Conditionals: if, switch & ternary
How to make your code think and make decisions using if statements, switch cases, and the concise ternary operator.
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
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
ifstatements evaluate whether a condition is truthy or falsy.switchstatements use strict equality (===) and require abreakto 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.