布尔值 Logic
Deepen 你的理解的 真/假值, logical 运算符, truthiness, and 短-circuit evaluation.
你将学到
- three logical 运算符: AND, OR, NOT
- 什么 truthy and falsy 值是 in JavaScript
- 短-circuit evaluation and 它的 practical uses
- 如何 组合 and negate 条件 effectively
- De Morgan's laws for simplifying 复杂条件
概念讲解
Boolean Logic
Boolean logic is the foundation of all decision-making in programming. Every if statement, every loop condition, and every filter operation ultimately evaluates to a single boolean value: true or false. Understanding how logical operators combine and transform these values is critical for writing correct conditions.
The Three Logical Operators
- AND (
&&) — returns真only if *both* operands are true. Think of it as "所有条件必须通过." - OR (
||) — returns真if *either* operand is true. Think of it as "at 最少 one 条件必须通过." - NOT (
!) — inverts a boolean:!真is假,!假is真.
const age = 25;
const hasLicense = true;
const canDrive = age >= 16 && hasLicense; // true (both conditions met)
const isWeekend = false;
const isHoliday = true;
const dayOff = isWeekend || isHoliday; // true (at least one is true)
const isBlocked = !canDrive; // false (inverted)
Truthy and Falsy
JavaScript does not require strict boolean values in conditions. Every value is classified as either truthy or falsy. The falsy values are: 假, 0, "" (empty string), 空, undefined, and NaN. Everything else is truthy — including non-empty strings, non-zero numbers, and all objects.
if ("hello") { /* runs — non-empty string is truthy */ }
if (0) { /* skipped — 0 is falsy */ }
if ([]) { /* runs — empty array is truthy! */ }
Short-Circuit Evaluation
The && and || operators short-circuit: they stop evaluating as soon as the result is determined. For &&, if the left side is falsy, the right side is never evaluated. For ||, if the left side is truthy, the right side is never evaluated.
This is not just a performance detail — it is a powerful idiom for providing default values and guarding against undefined:
const config = userSettings || defaults; // use defaults if userSettings is falsy
const name = user && user.name; // safe access: won't error if user is null
Combining Conditions
Complex conditions can be built by chaining operators. Use parentheses to make the grouping explicit — relying on default precedence is a common source of bugs:
if ((isAdmin || isEditor) && !isSuspended) {
// allow access
}
De Morgan's Laws
Two transformation rules help simplify and invert conditions: !(&& b) is equivalent to ! || !b, and !(|| b) is equivalent to ! && !b. These laws let you rewrite negated compound conditions into simpler forms, which often read more naturally.
示例代码
// Form validation using boolean logic
function isFormValid(email, password, age) {
const hasEmail = email.includes("@") && email.length > 5;
const hasPassword = password.length >= 8;
const isAdult = age >= 18;
// All three must be true (AND logic)
return hasEmail && hasPassword && isAdult;
}
// Short-circuit for default values
function getDisplayName(user) {
// If user is null OR user.name is empty, fall back to "Guest"
return user?.name || "Guest";
}
// Using NOT to check for absence
const errors = [];
const isValid = !errors.length; // true when array is empty (0 is falsy)
console.log(isFormValid("[email protected]", "secure123", 25)); // true
console.log(isFormValid("bad", "short", 15)); // false
console.log(getDisplayName(null)); // "Guest"
console.log(isValid); // true
validator 组合 three 条件使用 AND. display name 函数 uses 短-circuit OR for 默认. isValid 检查 uses NOT on 数组长度 — 空数组有 长度 0 (falsy), 所以 !0 是真.
动手试一试
- 密码 Strength Analyser
密码规则是 布尔值 logic in 操作: 长度 >= 8 AND hasUpper AND hasDigit AND hasSymbol.
- Regex Tester
Regular 表达式 ultimately produce 布尔值 results (match or 否 match). 测试模式 and see logic.
常见错误
错误写法
Using ! 到 negate compound 条件不使用 parentheses.
正确做法
!(&& b) negates 整个表达式. ! && b 仅 negates . 总是 use parentheses 围绕表达式你 想要到 invert.
错误写法
Assuming 空数组 and 对象是 falsy.
正确做法
In JavaScript, [] and {} 是 truthy. 仅假, 0, '', 空, undefined, and NaN 是 falsy. 检查数组.长度 === 0 or 对象.键(obj).长度 === 0 相反.
错误写法
Relying on 运算符 precedence 相反的 using parentheses.
正确做法
总是 use parentheses in compound 条件. !(|| b) && c 是 clearer than relying on 默认 precedence 的 ! over && over ||.
相关资源
相关速查表
- JavaScript Cheatsheet
引用 for 所有 logical 运算符, truthy/falsy 值, and 短-circuit behavior.
练习 布尔值 Logic
9 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。