JavaScript Conditional Statements
Conditional statements give your program the power to make decisions — taking different paths based on different situations. Without them, your code would just run top to bottom with no branching; with them, your program can think and choose like a human.
if Statement
The most basic conditional: if the condition is true, execute the code inside the curly braces.
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>if Statement</title></head>
<body>
<div id="output"></div>
<script>
let age = 20;
if (age >= 18) {
document.getElementById('output').textContent = 'You are an adult';
}
</script>
</body>
</html>
You can omit the curly braces when there's only one statement inside, but it's strongly discouraged — braces make your code clearer and prevent bugs when you add more statements later.
if...else Statement
A binary choice: if the condition is true, run the if block; otherwise, run the else block.
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>if...else</title></head>
<body>
<div id="output"></div>
<script>
let score = 45;
if (score >= 60) {
document.getElementById('output').textContent = 'Passed!';
} else {
document.getElementById('output').textContent = 'Not passed, keep trying';
}
</script>
</body>
</html>
if...else if...else
Multiple conditions evaluated from top to bottom — the first one that matches gets executed, and the rest are skipped:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>if...else if</title></head>
<body>
<div id="output"></div>
<script>
let score = 85;
if (score >= 90) {
document.getElementById('output').textContent = 'Excellent';
} else if (score >= 80) {
document.getElementById('output').textContent = 'Good';
} else if (score >= 60) {
document.getElementById('output').textContent = 'Pass';
} else {
document.getElementById('output').textContent = 'Fail';
}
</script>
</body>
</html>
Example: Grade Calculator
<!DOCTYPE html>
<html>
<body>
<h2>Grade Calculator</h2>
<input type="number" id="score" placeholder="Enter score (0-100)">
<button onclick="checkGrade()">Check Grade</button>
<p id="result"></p>
<script>
function checkGrade() {
let score = Number(document.getElementById('score').value);
let grade = '';
let color = '';
if (score >= 90) {
grade = 'Excellent 🌟';
color = 'green';
} else if (score >= 80) {
grade = 'Good 👍';
color = 'blue';
} else if (score >= 70) {
grade = 'Average 😐';
color = 'orange';
} else if (score >= 60) {
grade = 'Pass 😅';
color = '#cc8800';
} else {
grade = 'Fail 😢';
color = 'red';
}
document.getElementById('result').innerHTML =
`<span style="color:${color};font-size:24px">${score} - ${grade}</span>`;
}
</script>
</body>
</html>
Ternary Operator
The ternary operator is a shorthand for if...else, ideal for simple binary choices:
<script>
// Syntax: condition ? value1 : value2
let age = 20;
let status = age >= 18 ? 'Adult' : 'Minor';
// Equivalent to:
let status2;
if (age >= 18) {
status2 = 'Adult';
} else {
status2 = 'Minor';
}
</script>
if...else — readability matters more than brevity.
switch Statement
When checking a single variable against multiple fixed values, switch is cleaner than if...else if:
<script>
let day = 3;
switch (day) {
case 1: console.log('Monday'); break;
case 2: console.log('Tuesday'); break;
case 3: console.log('Wednesday'); break;
// ...
default: console.log('Invalid number');
}
</script>
Two key points:
- Never omit
break— without it, execution "falls through" to the next case defaultis the catch-all — runs when no case matches
Example: Switch Fall-through Pitfall
<!DOCTYPE html>
<html>
<body>
<h2>Switch Statement Demo</h2>
<p id="output"></p>
<script>
let html = '<strong>With break:</strong><br>';
let fruit = 'apple';
switch (fruit) {
case 'apple': html += 'Apple<br>'; break;
case 'banana': html += 'Banana<br>'; break;
default: html += 'Unknown fruit<br>';
}
html += '<br><strong>Without break (fall-through):</strong><br>';
let num = 2;
switch (num) {
case 1: html += 'One<br>';
case 2: html += 'Two<br>';
case 3: html += 'Three<br>';
default: html += 'Default<br>';
}
// Output: Two, Three, Default — starts at match and runs to the end
html += '<br><strong>Using fall-through intentionally:</strong><br>';
let month = 2;
let season = '';
switch (month) {
case 3: case 4: case 5: season = 'Spring'; break;
case 6: case 7: case 8: season = 'Summer'; break;
case 9: case 10: case 11: season = 'Autumn'; break;
case 12: case 1: case 2: season = 'Winter'; break;
}
html += `Month ${month} is ${season}`;
document.getElementById('output').innerHTML = html;
</script>
</body>
</html>
break is the most common switch bug. But sometimes "fall-through" is useful — when multiple values should run the same logic, intentionally omitting break lets them merge.
falsy Values
In conditional checks, the following values are treated as false (called falsy values):
| falsy value | Description |
|---|---|
false |
Boolean false |
0 |
Zero |
"" or '' |
Empty string |
null |
Null |
undefined |
Undefined |
NaN |
Not a Number |
All other values are truthy, including "0" (string zero), [] (empty array), {} (empty object) — these may look "empty," but they evaluate to true in conditions.
Example: Falsy Value Checks
<!DOCTYPE html>
<html>
<body>
<h2>Falsy Values Demo</h2>
<p id="output"></p>
<script>
let html = '<strong>Falsy values (evaluate to false):</strong><br>';
let falsy = [false, 0, "", null, undefined, NaN];
for (let val of falsy) {
let display = val === "" ? '""' : (val === undefined ? 'undefined' : val);
html += `${display} → ${val ? 'truthy' : 'falsy'}<br>`;
}
html += '<br><strong>Tricky truthy values:</strong><br>';
let tricky = ["0", [], {}, "false", -1];
for (let val of tricky) {
let display = Array.isArray(val) ? '[]' : (typeof val === 'object' ? '{}' : JSON.stringify(val));
html += `${display} → ${val ? 'truthy' : 'falsy'}<br>`;
}
html += '<br><strong>Practical example:</strong><br>';
let name = '';
html += `Name: "${name}" → ${name || 'Not provided'}<br>`;
let count = 0;
html += `Count: ${count} → ${count || 'None'} (0 is treated as falsy!)<br>`;
html += `Correct way: ${count !== undefined && count !== null ? count : 'None'}`;
document.getElementById('output').innerHTML = html;
</script>
</body>
</html>
|| for default values, watch out: 0 and "" are valid but get treated as falsy. Use ?? (nullish coalescing operator) instead — it only applies the default for null and undefined.
📖 Summary
if...else if...elseevaluates top to bottom, executing the first match and skipping the rest- Ternary operator is shorthand for
if...else— good for simple assignments, not for complex logic switchis cleaner for matching fixed values, but don't forgetbreak- Six falsy values:
false,0,"",null,undefined,NaN "0",[],{}are truthy — don't be fooled by their "empty" appearance- Be careful with
||for defaults when0and""are valid — use??or explicit comparisons
❓ FAQ
== and === in conditionals?== performs type coercion before comparing ("1" == 1 is true), while === does not ("1" === 1 is false). Always use === to avoid unexpected implicit conversions.switch compare strings?switch works with strings, numbers, and booleans — it uses strict equality (===) for comparison.?? and ||?|| triggers on all falsy values (0, "", null, undefined, NaN, false), while ?? only triggers on null and undefined. Use ?? when you need to preserve 0 and empty strings.📝 Exercises
- Write a program that takes a year as input and determines if it's a leap year (divisible by 4 but not by 100, or divisible by 400)
- Build a simple calculator: take two numbers and an operator (+, -, *, /) as input, use
switchto compute the result, and handle division by zero - Build a BMI calculator: take height (m) and weight (kg) as input, calculate BMI, and display the category (underweight/normal/overweight/obese)



