Conditionals let a program make decisions instead of running the exact same line-by-line steps every time. This lesson covers if/else and else-if chains, truthy and falsy values, the switch statement, and how to combine conditions with && and || logical operators.
1JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 1
Welcome to JavaScript Conditionals. Programs need to make decisions. Without conditions, a script runs line-by-line doing the exact same thing every time. Today, we give our code a 'Choice'.
// Conditionals: The Art of Decision MakingDecision Making
2JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 2
The 'if' statement is the most basic building block. It evaluates a condition in parentheses. If that condition is true, the block of code inside the curly braces runs.
let age = 20;
if (age >= 18) {
console.log('Access Granted');
}If Statement
3JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 3
What if the condition is false? We use 'else' to provide a fallback path. This ensures our program always has a clear instruction, no matter the input.
if (age >= 18) {
console.log('Yes');
} else {
console.log('No');
}Else Statement
4JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 4
For multiple options, use ''else if'. You can chain as many as you need, but remember: only the FIRST true block will execute.
if (score >= 90) {
// A
} else if (score >= 80) {
// B
} else {
// F
}Else If
5JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 5
JavaScript also evaluates non-Boolean values. Values like 0, empty strings (''), null, and undefined are 'Falsy'. Almost everything else is 'Truthy'.
let name = '';
if (name) {
// This won't run because '' is falsy
}Truthy & Falsy
6JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 6
For many specific discrete values, the ''switch' statement is often cleaner. It compares an expression against multiple 'case' labels.
switch (role) {
case 'admin': return 'Full Access';
case 'user': return 'Read Access';
default: return 'No Access';
}Switch Statement
7JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 7
Watch the render. See how the code flow branches and jumps across different logic blocks based on the dynamic state of the application.'
/* Condition Lab: Logic Branching Rendered */Logic Execution
8JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 8
Comparison vs Assignment: Be careful! Using a single '=' inside an 'if' is an assignment, which is usually a bug. Always use '===' for comparison.
// ❌ if (score = 100) // Always true!
// ✅ if (score === 100) // Correct checkComparison vs Assignment
9JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 9
Logical combination: You can check multiple conditions at once using && (AND) and || (OR). This allows for very specific branching logic.'
if (isAdult && hasTicket) { ... }Logical Operators
10JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 10
Conditional patterns are the architecture of interactivity. They allow your site to respond to user input with intelligence and precision.'
// Logic Architecture: CompleteInteractivity
11JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 11
You'
console.log('Logic Path: Verified');Verified
12JS Conditionals | JavaScript Tutorial - In-Depth Guide Part 12
Conditional mastery achieved! Now let'
/* Next: JavaScript Loops (Iteration) */On to Loops
13Step-by-Step Breakdown
Welcome to JavaScript Conditionals. Programs need to make decisions. Without conditions, a script runs line-by-line doing the exact same thing every time. Today, we give our code a 'Choice'.
The 'if' statement is the most basic building block. It evaluates a condition in parentheses. If that condition is true, the block of code inside the curly braces runs.
What if the condition is false? We use 'else' to provide a fallback path. This ensures our program always has a clear instruction, no matter the input.
Checkpoint: Which keyword is used to provide a secondary path when the initial 'if' condition fails?
- →else
- →then
For multiple options, use ''else if'. You can chain as many as you need, but remember: only the FIRST true block will execute.
JavaScript also evaluates non-Boolean values. Values like 0, empty strings (''), null, and undefined are 'Falsy'. Almost everything else is 'Truthy'.
For many specific discrete values, the ''switch' statement is often cleaner. It compares an expression against multiple 'case' labels.
Watch the render. See how the code flow branches and jumps across different logic blocks based on the dynamic state of the application.'
Checkpoint: What is the Boolean result of an empty string ('') in a conditional check?
- →True (Truthy)
- →False (Falsy)
Comparison vs Assignment: Be careful! Using a single '=' inside an 'if' is an assignment, which is usually a bug. Always use '===' for comparison.
Logical combination: You can check multiple conditions at once using && (AND) and || (OR). This allows for very specific branching logic.'
Conditional patterns are the architecture of interactivity. They allow your site to respond to user input with intelligence and precision.'
You'
Checkpoint: Which keyword should you use to handle 'everything else' that didn't match any specific 'if' or 'else if' condition?
- →else
- →default
Conditional mastery achieved! Now let'
Level Up 🚀
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1Don't Hide Critical UI Behind JavaScript-Only Conditional Rendering
If a menu, warning message, or form validation error only appears based on a client-side conditional that assumes JavaScript ran successfully, users on assistive technology relying on server-rendered content or with JS disabled/failed may never see it — ensure critical conditional UI has a non-JS fallback or is rendered server-side.
<noscript>Please enable JavaScript to use this form.</noscript>SEO Implications
- 1
Content Gated Behind a Client-Side Condition May Not Be Indexed
If important text only renders after a conditional check that depends on client-side state (e.g. `if (isLoggedIn) { showContent() }` or a condition that only becomes true after a user interaction), search engine crawlers that don't fully execute your JavaScript may index a page that appears empty or incomplete.
Best Practices
Use Strict Equality (===) Instead of Loose Equality (==) in Conditions
== performs type coercion before comparing (so '' == false is true, and 0 == '0' is true), which produces confusing, hard-to-predict results. === compares both value and type with no coercion, making conditional logic far more predictable.
Guard Against a Single '=' Inside an if Condition
if (score = 100) is a valid assignment expression, not a comparison — it sets score to 100 and the condition is always truthy. Most linters flag this, but it's still one of the most common typo-driven bugs in conditional code; always double- or triple-check your equality operators.
Frequent Bugs
A switch statement runs multiple case blocks when only one was expected.
This happens when a `break` statement is missing at the end of a case — execution 'falls through' into the next case regardless of whether its label matches. Add a `break` (or `return`, inside a function) at the end of every case block unless fall-through is intentional.
Real-World Examples
Validating Form Input Before Submission
A signup form needed to block submission and show an inline error unless the email field was non-empty and contained an '@' character, avoiding a round trip to the server for obviously invalid input.
function validateEmail(value) {
if (!value || !value.includes('@')) {
return 'Please enter a valid email address.';
}
return null;
}