Conditionals in JavaScript
Learn how to make decisions in your code with conditional statements.
What are Conditionals?
Conditionals allow your code to make decisions based on certain conditions. They're the foundation of program logic - "if this, then do that."
Key Concept: Conditionals evaluate expressions to
true or false (boolean values) and execute different code blocks accordingly.
The if Statement
The simplest conditional. If the condition is true, the code block runs.
Try it yourself
Output
if...else Statements
Use else to specify what happens when the condition is false.
Try it yourself
Output
if...else if...else
Chain multiple conditions together for more complex logic.
Try it yourself
Output
Comparison Operators
Use these operators to compare values in conditions:
Try it yourself
Output
Best Practice: Always use
=== and !== (strict equality) to avoid unexpected type coercion bugs.
Logical Operators
Combine multiple conditions using AND (&&), OR (||), and NOT (!).
Try it yourself
Output
The Switch Statement
Use switch when you need to compare a value against many options.
Try it yourself
Output
The Ternary Operator
A shorthand for simple if...else statements: condition ? valueIfTrue : valueIfFalse
Try it yourself
Output
Challenge: Age Validator
Create a function that takes an age and returns:
- "Child" if age is under 13
- "Teenager" if age is 13-19
- "Adult" if age is 20-64
- "Senior" if age is 65 or older
Your solution
Output