Skip to content

条件

如果/else, 切换, ternary 运算符, truthy/falsy 值, and 短-circuit evaluation.

你将学到

  • 如果, else 如果, and else 语句
  • 切换语句 for multi-方式 branching
  • ternary 运算符 for concise conditionals
  • Truthy and falsy 值 in JavaScript
  • 短-circuit evaluation 使用 && and ||

概念讲解

if / else if / else

The fundamental branching construct:

const score = 85;

if (score >= 90) {
  console.log("");
} else if (score >= 80) {
  console.log("B");
} else if (score >= 70) {
  console.log("C");
} else {
  console.log("F");
}

switch

Use 切换 when comparing one value against many constants. Always include break or execution falls through to the next case:

const day = "Monday";
switch (day) {
  case "Monday":
  case "Tuesday":
    console.log("开始的 week");
    break;
  case "Friday":
    console.log("Almost weekend");
    break;
  default:
    console.log("Midweek");
}

The Ternary Operator

A concise if/else that returns a value:

const age = 20;
const status = age >= 18 ? "adult" : "minor";

Nesting ternaries is possible but hurts readability — prefer if/else for complex logic.

Truthy and Falsy

In a boolean context, these values are falsy: 假, 0, "", 空, undefined, NaN, 0n. Everything else is truthy — including "0", [], and {}.

if ("0") console.log("运行");     // strings are truthy (even "0")
if ([]) console.log("运行");      // arrays are truthy (even empty)
if (0) console.log("skipped");    // 0 is falsy

Short-Circuit Evaluation

&& returns the first falsy value (or the last value if all are truthy). || returns the first truthy value. This is handy for defaults and guards:

const config = { timeout: 0 };
const timeout = config.timeout || 3000; // 3000 — but 0 is a valid timeout!

// Use ?? (nullish coalescing) for this case
const safeTimeout = config.timeout ?? 3000; // 0 — only null/undefined trigger the default

Prefer ?? (ES2020) when 0 or "" are valid values, because || treats them as falsy.

示例代码

              // if / else if / else
function grade(score) {
  if (score >= 90) return "A";
  if (score >= 80) return "B";
  if (score >= 70) return "C";
  if (score >= 60) return "D";
  return "F";
}
console.log("Grade for 85:", grade(85));

// Ternary operator
const hour = 14;
const period = hour < 12 ? "morning" : hour < 18 ? "afternoon" : "evening";
console.log("It is", period);

// Short-circuit for defaults
const user = { name: "", age: 0 };
const displayName = user.name || "Anonymous"; // "Anonymous" — empty string is falsy
const displayAge = user.age ?? 18;             // 0 — nullish coalescing keeps 0
console.log(displayName, displayAge);

// switch with fall-through grouping
function getDayType(day) {
  switch (day) {
    case "Saturday":
    case "Sunday":
      return "weekend";
    default:
      return "weekday";
  }
}
console.log("Saturday is a", getDayType("Saturday"));
            

Shows 如果/else chaining, nested ternaries, 短-circuit || for defaults, nullish coalescing ?? 到 preserve 0 and 空字符串, and 切换使用 intentional fall-通过.

动手试一试

  • Math Evaluator

    Evaluate 表达式那个经常 appear in 条件.

  • Regex Tester

    Regex 测试 results 是经常 used in 如果条件.

常见错误

错误写法

Using || for defaults 当 0 or 空字符串是 有效值

正确做法

|| treats 0, '', and 假 as falsy. Use nullish coalescing 运算符 ?? (ES2020) 哪个仅 falls 后面 on 空 or undefined.

错误写法

Forgetting break in 切换语句

正确做法

不使用 break, execution falls 通过到 下一个情况. 总是添加 break (or 返回) 除非你 intentionally 想要 fall-通过. 分组情况 intentionally as shown in 示例.

相关速查表

练习 条件

9 个练习

练习 条件

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误