JavaScript: 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.
1. if Statement
The most basic conditional: if the condition is true, execute the code inside the curly braces.
<!-- Document type declaration -->
<!DOCTYPE html>
<!-- HTML root element -->
<html lang="en">
<!-- Document head -->
<head><meta charset="UTF-8"><title>if Statement</title></head>
<!-- Document body -->
<body>
<!-- Container element -->
<div id="output"></div>
<!-- Script tag -->
<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.
2. if...else Statement
A binary choice: if the condition is true, run the if block; otherwise, run the else block.
<!-- Document type declaration -->
<!DOCTYPE html>
<!-- HTML root element -->
<html lang="en">
<!-- Document head -->
<head><meta charset="UTF-8"><title>if...else</title></head>
<!-- Document body -->
<body>
<!-- Container element -->
<div id="output"></div>
<!-- Script tag -->
<script>
let score = 45;
if (score >= 60) {
document.getElementById('output').textContent = 'Passed!';
} else {
document.getElementById('output').textContent = 'Not passed, keep trying';
}
</script>
</body>
</html>
3. if...else if...else
Multiple conditions evaluated from top to bottom — the first one that matches gets executed, and the rest are skipped:
<!-- Document type declaration -->
<!DOCTYPE html>
<!-- HTML root element -->
<html lang="en">
<!-- Document head -->
<head><meta charset="UTF-8"><title>if...else if</title></head>
<!-- Document body -->
<body>
<!-- Container element -->
<div id="output"></div>
<!-- Script tag -->
<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
▶ Try it Yourself4. Ternary Operator
The ternary operator is a shorthand for if...else, ideal for simple binary choices:
<!-- Script tag -->
<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.
5. switch Statement
When checking a single variable against multiple fixed values, switch is cleaner than if...else if:
<!-- Script tag -->
<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
▶ Try it Yourselfbreak 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.
6. 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
▶ Try it Yourself|| 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.
❓ FAQ
== and === in conditional checks in JavaScript?== performs type conversion before comparing, so "1" == 1 is true; === does not convert, so "1" === 1 is false. In conditional checks it is recommended to use === consistently to avoid unexpected results caused by implicit conversion.?? and || in JavaScript conditional statements?|| applies to all falsy values, so 0, "", null, undefined, NaN, and false all fall back to the default value; ?? only applies to null and undefined. Use ?? when you need to preserve 0 or an empty string, otherwise you may get a wrong result.! to negate, for example if (!isLogin) { ... } means it runs when isLogin is falsy. You can also write if (isLogin === false) for a strict comparison, but !isLogin is more common.📖 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
📝 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)