404 Not Found

404 Not Found


nginx

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.

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.

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>

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

HTML
<!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>
▶ Try it Yourself

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

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

HTML
<!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>
▶ Try it Yourself
⚠️ 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.

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

HTML
<!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>
▶ Try it Yourself
⚠️ 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.


📖 Summary

  1. if...else if...else evaluates top to bottom, executing the first match and skipping the rest
  2. Ternary operator is shorthand for if...else — good for simple assignments, not for complex logic
  3. switch is cleaner for matching fixed values, but don't forget break
  4. Six falsy values: false, 0, "", null, undefined, NaN
  5. "0", [], {} are truthy — don't be fooled by their "empty" appearance
  6. Be careful with || for defaults when 0 and "" are valid — use ?? or explicit comparisons

❓ 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.

📝 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)
100%

🙏 帮我们做得更好

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

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