JavaScript: JavaScript Conditional Statements

Last updated: 2026-10-13

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.

Related Statements:if...else switch

1. if Statement

The most basic conditional: if the condition is true, execute the code inside the curly braces.

HTML
<!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.


2. if...else Statement

A binary choice: if the condition is true, run the if block; otherwise, run the else block.

HTML
<!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>

3. if...else if...else

Multiple conditions evaluated from top to bottom — the first one that matches gets executed, and the rest are skipped:

HTML
<!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

▶ Try it Yourself

4. Ternary Operator

The ternary operator is a shorthand for if...else, ideal for simple binary choices:

HTML
<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>
💡 Tip: The ternary operator is great for simple value assignments. When logic gets complex, stick with 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:

HTML
<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:

  1. Never omit break — without it, execution "falls through" to the next case
  2. default is the catch-all — runs when no case matches

▶ Example: Switch Fall-through Pitfall

▶ Try it Yourself
⚠️ Note: Forgetting 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.


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
⚠️ Note: When using || 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.


Related Statements:if...else switch

❓ FAQ

Q What's the difference between == and === in conditionals?
A == performs type coercion before comparing ("1" == 1 is true), while === does not ("1" === 1 is false). Always use === to avoid unexpected implicit conversions.
Q Can switch compare strings?
A Yes. switch works with strings, numbers, and booleans — it uses strict equality (===) for comparison.
Q What's the difference between ?? and ||?
A || 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.

📖 Summary

📝 Exercises

  1. 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)
  2. Build a simple calculator: take two numbers and an operator (+, -, *, /) as input, use switch to compute the result, and handle division by zero
  3. Build a BMI calculator: take height (m) and weight (kg) as input, calculate BMI, and display the category (underweight/normal/overweight/obese)
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏